371. Sum of integers
- Total accepted:10773
- Total submissions:20732
- Difficulty:easy
Calculate the sum of of the integers a and b, but is not allowed to use the operator + and - .
Example:
Given a = 1 and b = 2, return 3.
Idea: Using binary bit operations to achieve number addition. Just find the carry, add it to the XOR result.
With the action & filter out the bits that can be rounded, and then move those bits 1 bits to the left, equal to the carry, Xor ^ can filter out the bits without rounding.
For the binary operation principle, you can refer to the bits operation.
Code:
Iteration:
1 classSolution {2 Public:3 intGetsum (intAintb) {4 intcarry;5 while(b) {6carry= (a&b) <<1;7A=a^b;8b=carry;9 }Ten returnA; One } A};
Recursion:
1 class Solution {2 public:3 int getsum (int a, int b) {4 if (!b) return a;5 return Getsum (A^b, (a&b) <& LT;1); 6 }7};
There are also subtraction and inverse numbers in the int range without the + and-implementation:
1 //iterative2 Public intGetsubtract (intAintb) {3 while(b! =0) {4 intBorrow = (~a) &b;5A = a ^b;6b = Borrow <<1;7 }8 9 returnA;Ten } One A //Recursive - Public intGetsubtract (intAintb) { - return(b = =0) ? A:getsubtract (a ^ B, (~a & B) <<1); the } - - //Get Negative number - Public intNegateintx) { + return~x +1; -}
Leetcode 371. Sum of integers