[LintCode] A + B 问题

时间:2020-11-28 18:19:54

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:

  1. a + b without carry;
  2. carry of a + b;
  3. 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) << ));
}
};