首页 > 代码库 > Sum of Two Integers

Sum of Two Integers

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.

 

 1 class Solution {
 2 public:
 3     int getSum(int a, int b) {
 4         int base = 0, result = 0, carry = 0;
 5         while (base < 32) {
 6             // get the last bit of a and b, xor with carry
 7             int tempA = a & 1, tempB = b & 1;
 8             int current = (tempA ^ tempB ^ carry) << base;
 9             result |= current;
10             carry = (tempA & tempB) || (tempA & carry) || (tempB & carry);
11             a >>= 1;
12             b >>= 1;
13             base++;
14         }
15         return result;
16     }
17 };

 

Sum of Two Integers