Problem:
thesumoftwoaandnottotheanda1and2return3.
Analysis:
This requires that we do not use addition, subtraction and other operators to implement the addition operation. This should be done by using bitwise operations, which is, in fact, the implementation of the addition operation within the CPU of the computer.
x XOR y truth table:
X y output
0 0 0
0 1 1
1 0 1
1 1 0
X and Y truth table:
X y output
0 0 0
0 1 0
1 0 0
1 1 1
We can use & and ^ operations to achieve addition based on the truth table above, and each of the ^ operations gets the non-rounding of each one and the carry of each bit with the & operation.
According to the above analysis, we can add each x, Y and each one to perform XOR and and operations, and then get the final result. But if you want to get each bit, you also use the and operation.
Say 00001010,
To take the second-lowest value (1), the value is: 00001010&00000010
To take the third-lowest value (0), the value is: 00001010&00000100
To take the fourth-lowest value (1), the value is: 00001010&00001000
And that's not really going to get the value on each one, but also the action.
First, we get the carry on each one by doing a & bit operation on X and Y. The x and y are then performed with the ^ bitwise operation, resulting in no added and rounding. Finally, the resulting and as New X, the resulting carry to the left one (the 0th digit of the carrying input is 0) as the new Y, continue to do the above steps until the rounding is 0, at which point the X and Y are saved is the same.
Code:
class solution { public : int getsum (int A, int b) {int sum = A; int icarry = b; while (Icarry!=0 ) {int tmp = sum ; sum = tmp ^ Icarry; Icarry = (tmp&icarry) <<1 ; } return sum ; }};
[Leetcode] Sum of two integers--with bitwise operations for addition operations