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
****************************************************************/