LeetCode-371 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.

The trick of this problem is to use bit manipulation to implement + and - operators.

Summary of using Bit Manipulation

class Solution {
    public int getSum(int a, int b) {
        if(a==0) return b;
        while(b!=0){
            int carry = a&b;
            a=a^b;
            b=carry<<1;
        }
        return a;
    }
}

Detailed Explanation

For this, problem, for example, we have a = 1, b = 3,

In bit representation, a = 0001, b = 0011,

First, we can use “and”(“&”) operation between a and b to find a carry.

carry = a & b, then carry = 0001

Second, we can use “xor” (“^”) operation between a and b to find the different bit, and assign it to a,

Then, we shift carry one position left and assign it to b, b = 0010.

Iterate until there is no carry (or b == 0)

Source

And the subtraction:

// Iterative
public int getSubtract(int a, int b) {
    while (b != 0) {
        int borrow = (~a) & b;
        a = a ^ b;
        b = borrow << 1;
    }

    return a;
}

How would you add two integers using bit manipulation? You cannot use any arithmetic operators.