Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
  • Examples:
Given a = 1 and b = 2, return 3.
  • Analysis:
Use XOR and AND to present sum and carry until carry is zero.

-------------------------
| x | y | x ^ y | x & y |     carry = x ^ y
-------------------------
| 0 | 0 |   0   |   0   |     sum = x & y
-------------------------
| 0 | 1 |   1   |   0   |
-------------------------
| 1 | 0 |   1   |   0   |
-------------------------
| 1 | 1 |   0   |   1   |
-------------------------
  • Code - Java:
class Solution {
    public int getSum(int a, int b) {
        int carry = (a & b) << 1;
        int result = a ^ b;
        while (carry != 0) {
            int tempCarry = (result & carry) << 1;
            result = result ^ carry;
            carry = tempCarry;
        }
        return result;
    }
}
  • Code - C++:
class Solution {
public:
    int getSum(int a, int b) {
        int carry = (a & b) << 1;
        int result = a ^ b;
        while (carry != 0) {
            int tempCarry = (result & carry) << 1;
            result = result ^ carry;
            carry = tempCarry;
        }
        return result;
    }
};
  • Code - C:
int getSum(int a, int b) {
    int carry = (a & b) << 1;
    int result = a ^ b;
    while (carry != 0) {
        int tempCarry = (result & carry) << 1;
        result = result ^ carry;
        carry = tempCarry;
    }
    return result;
}

results matching ""

    No results matching ""