Title: Implement the int add (int a, int b) method to implement the sum of A and B, but do not allow arithmetic operations such as +-*/to be used internally.
Answer: This question is actually how to do the addition of computer hardware. The addition and multiplication in the computer is the method of simulating the addition and multiplication of the man to design and implement the CPU arithmetic operation module. This should be learned when we learn the principles of computer composition. As in the following example:
1101
11
+
--------------
10000
This calculation can be divided into two parts, part of the bitwise + process, and the other part is the process of rounding.
Bitwise +, in fact, is the XOR operation, 1+1=0, 1-bit, 0+1=1+0=1,0+0=0
How does the carry count? In what case carry, when the only carry, you should immediately be able to think and operation. Added to the high to continue the next operation. Then we can get the following formula:
a+b=a^b+ (a&b) <<1
It also uses the addition, cannot solve our problem, but you do not think this is a recursion?
Add (A, b) =add (A^b, (a&b) <<1)
So when does this recursion end? Obviously, one of a or B is 0, and surely it can be terminated.
Here's the code:
int add (int a, int b) { if (!a) return B; else return Add ((A & B) << 1, a ^ b);}
Do not use subtraction to do the problem of addition