Without using the plus addition

We mostly use the addition of two numbers when adding process of adding direct operation, no doubt.

But at the same time how not to use two numbers plus the completion of the addition operation?

 1 #include <iostream>
 2 
 3 using namespace std;
 4 int add1(int a, int b)
 5 {
 6     int x, y;
 7     while (b != 0)
 8     {
 9         x = a ^ b;
10         y = (a&b) << 1;
11         a = x;
12         b = y;
13         
14     }
15     return a;
16 }
17 int main()
18 {
19     cout << add1(6, 3) << endl;
20     return 0;
21 }

This method is used to complete the addition of two-bit arithmetic numbers.

In which x represents the sum of two numbers, y is representative of the carry flag.

It is assumed that the use and addition of 63, to give left shift operation by two and the number of exclusive OR operation and an add operation.

6  :0110

3 : 0011

The first step after x: 0101 y: 0100

After Step x: 0001 y: 1000

After the third x: 1001 y: 0000

B is 0 this time, out of determination, return the value of x

This time the value of x 9, to obtain the results of adding 6 and 3.

Guess you like

Origin www.cnblogs.com/programchen/p/12324830.html