Bit-by-Bit summation:
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
int res = , sum = , carry = ;
for (int i = ; i < ; i++, a >>= , b >>= ){
int d1 = a & , d2 = b & ;
sum = (d1 ^ d2 ^ carry);
carry = max((d1 & d2), max((d1 & carry), (d2 & carry)));
res ^= (sum << i);
}
return res;
}
};
Treat a + b as two parts:
- a + b without carry;
- carry of a + b;
- recursively plus part 1 and part 2 until no carry exists.
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
while (b) {
int carry = a & b; // carry
a ^= b; // plus without carry
b = carry << ; // recursively plus the two parts
}
return a;
}
};
The code can be further shortened by writing it recursively.
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
if (!b) return a;
return aplusb(a ^ b, (a & b) << );
}
};
Or just in one line :-)
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
return (!b ? a : aplusb(a ^ b, (a & b) << ));
}
};