[Offoffoffer] addition without addition, subtraction, multiplication, division

Source: Internet
Author: User

Reprinted please indicate the source: http://blog.csdn.net/ns_code/article/details/27966641

Description:

Write a function and calculate the sum of two integers. The +,-, *, And/operators must not be used in the function.

Input:

The input may contain multiple test examples.
For each test case, enter two integers m and n (1 <= m, n <= 1000000 ).

Output:

Output m + n values for each test case.

Sample input:
3 47 9
Sample output:
716
Ideas:

1. Add all bits, excluding carry. This step can be implemented using m ^ n.

2. Add carry and carry to get the bit where both m and n are 1 with m & n, and the bit where not all are 1 is changed to 0, this addition of bits will carry the place, so that the one on the left is added with 1, so (m & n) <1 side can get the position of 1 to be added after the carry;

3. Add the results of the previous two steps, and generate carry during the addition. Therefore, the process of adding the two steps can repeat steps 1 and 2 again until (m & n) <1 is changed to 0. At this time, no carry is generated. Exit the loop.

The Code is as follows:

# Include <stdio. h> int AddNumThoughBit (int a, int B) {int sum; // do not include carry and int add1; // carry while (B! = 0) {sum = a ^ B; add1 = (a & B) <1; a = sum; B = add1;} return a;} int main () {int m, n; while (scanf ("% d", & m, & n )! = EOF) printf ("% d \ n", AddNumThoughBit (m, n ));}
/**************************************************************      Problem: 1507      User: mmc_maodun      Language: C      Result: Accepted      Time:10 ms      Memory:912 kb ****************************************************************/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.