Question: implement the int add (int a, int B) method to implement the sum of a and B, but internal arithmetic operations such as +-*/are not allowed.
Answer: This question is actually about how to add computer hardware. The addition and multiplication in the computer simulate the addition and multiplication methods to design and implement the cpu arithmetic operation module. This should be learned in our course on computer composition principles. For example:
1101
11
+
--------------
10000
This computation can be divided into two parts: the bitwise + process and the carry process. Bitwise + is actually an exclusive or operation. 1 + 1 = 0, first digit, 0 + 1 = 1 + 0 = 1, 0 + 0 = 0. How can we calculate the carry? Under what circumstances is the carry-in and 1 + 1 time? You should be able to think about it immediately. The bit to be added to the high level to continue to participate in the next operation. We can get the following formula:
A + B = a ^ B + (a & B) <1
We still use addition, which cannot solve our problem, but do you think this is a recursion?
Add (a, B) = add (a ^ B, (a & B) <1)
When will this recursion end? Obviously, if one of a or B is 0, it can be terminated.
The following code is used:
Int add (int a, int B) {if (! A) return B; else return add (a & B) <1, a ^ B );}
This article from the "Yi fall Dusk" blog, please be sure to keep this source http://yiluohuanghun.blog.51cto.com/3407300/1294327