A very common problem, there are all kinds of solutions on the Internet, forget about it.
Let's start with the addition of the decimal integer, 123 + 999, and divide it into three steps:
(1) Add to each bit, regardless of rounding. When there is rounding, discard. As follows:
123
+ 999
= 012
(2) Consider the effect of rounding. Observation reveals that when the number of digits is added with a carry, it actually adds 10 less, and when the hundred has a carry, it actually adds 100 less, and so on. So, the second step we get is because the number of little plus is not considered. When no carry is 0, when there is carry, discard bits, leaving 10 bits. For example 5 + 6 = 11, discard bits, leave 10 bit, 1, that is 5 + 6 = 1. Do this to each of the following:
123
+ 999
= 111
Digit: 3 + 9 = 1 less plus 10
10-bit: 2 + 9 = 1 less plus 100
Hundred: 1 + 9 = 1 less plus 1000
A total of 1100, or 111 * 10 = 1110. Because it is a decimal, the number of 111 * 10 is added to the rounding, that is, the number that is omitted due to ignoring the rounding
(3) Add the numbers obtained from the first and second steps:
012
+ 1100
= 1112
Get the final result.
Extended to binary, every 2 into 1. Example: 15 + 11, converted to binary is: 1111 + 1011, or follow the above three steps:
(1) Each bit is added, regardless of rounding:
1111
+ 1011
= 0100
(2) Consider carry, calculate the number of small plus
1111
+ 1011
= 1011
Corresponds to binary, right to left:
First place carry: 2 less
Second rounding: 4 Less
Fourth digit: 16 less
Because it is binary, it needs to be 1011 * 2, corresponding to the binary, that is, moving left one bit, becomes 10110
(3) Add the number of the first and second steps:
0100 = 4
10110 = 22
and to: 26
When using binary addition:
0100
+ 10110
= 11010
In fact, in the above process there are still carry, continue to use the above method. Therefore, using binary to implement addition is actually a cyclic process.
Use the program to achieve the above steps:
In the first step, 1 + 1 = 0, 0 + 0 = 0, 1 + 0 = 1, 0 + 1 = 1, actually conforming to the XOR operation (same as 0, different 1)
In the second step, 1 + 1 = 1, 0 + 0 = 0, 1 + 0 = 0, 0 + 1 = 0, actually conforms to the operation (only 1 o'clock is 1)
The third step is to repeat the first step and the second step.
The code is as follows:
while (CIN >> n >> m) { while(m) { int sum = n ^ m; int temp = (n & M) <<1; = sum; = temp; } << n << endl; }
View Code
No subtraction to implement the addition of two positive integers