Here I only write the key code:
Int add (int n, intm)
{
If (M = 0) returnn; ①
Int sum = n ^ m; ②
Int carry = (N & M) <1; ③
Return add (sum, carry); ④
}
Before analyzing the code in each step, let's look at two examples:
The sum of two numbers without bits:
0000 0010------2
0000 0100------4
The result is:
0000 0110------6
Add the two numbers of incoming bits:
0000 0101------5
0000 0100------4
The result is:
20171001------9
First, we will introduce these two examples into the function to understand the execution process of the function by comparing the differences between the carry operation and the non-carry operation.
Define an add function and declare the two integer variables:
① When one of M and N is 0, the result returns another value. This statement is the final exit of the program.
② N and M perform an exclusive or operation. If m and n are not included in the sum, sum is the result. Otherwise, save the numeric value without carry. Continue with the following carry operation.
③ M and N perform phase and operation, and then shift 1 bit left. When a carry value is generated, m and n are 1 at the same time at the same position, and 1 at the end of the phase, and 1 at the left to get the carry value. The second and above carry, and so on. If there is no carry, carry is 0.
④ Recursive function return add (), and perform a similar operation on the sum and carry obtained by the preceding steps until no carry is generated, that is, carry = 0.
Note: If the analysis is incorrect, we hope you can point it out!