Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases
class Solution {
public:
int getSum(int a, int b) {
int sum = 0;
int carry = 0;
int num1 = a;
int num2 = b;
do{
sum = num1 ^ num2;
carry = num1 & num2;
carry <<= 1;
num1 = sum;
num2 = carry;
}while(carry!=0);
return sum;
}
};