Java Iterative Solution


  • 0
    R

    Looks like the safe guards weren't necessary, as there were no overflow/underflow cases in the test.

    public int getSum(int a, int b) {
        final boolean over = a > 0 && b > 0;
        final boolean under = a < 0 && b < 0;
        int s;
        do {
            s = a ^ b;
            b = (a & b) << 1;
            a = s;
        } while (b != 0);
        if (over && s < 0) return Integer.MAX_VALUE;
        if (under && s > 0) return Integer.MIN_VALUE;
        return s;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.