[Sum of Two Integer] (https://leetcode.com/problems/sum-of-two-integers/#/description)

Problem

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.

Solution

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

Solution

Very easy problem by using bit manipulation
We use XOR to get the display value in each position (bit) of two numbers
Then we get the carry by left shifting one bit (a & b) << 1
At the end, we recursively call this function until the carry is 0
If you want one line, here it is return b == 0 ? a : getSum(a ^ b, (a & b) << 1);

results matching ""

    No results matching ""