PU Sum of Two Integers

Jan 01, 1970

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.

C Solution 1:

int getSum(int a, int b) {
    int carry;
    while (b) {
        carry = a & b;
        a ^= b;
        b = carry << 1;
    }
    return a;
}

C Solution 2:

int getSum(int a, int b) {
    if (!b) return a;
    int carry = (a & b) << 1;
    a ^= b;
    return getSum(a, carry);
}

Summary:

  • + can be implemented by ^ and &.
  • This is an experience, grasp it.

LeetCode: 371. Sum of Two Integers