Memory Overflow error for negative numbers - binary addition

Viewed 17

The below program binary addition on two integers and works fine for positive numbers, but causes overflow for negative numbers. (For e.g. inputs like 1,-1 fail). Last I checked It is happening because the carry overflows beyond the int capacity. How do I correct this?

public int getSum(int a, int b) {
        StringBuilder res = new StringBuilder();
        int carry = 0;
        while (a != 0 || b != 0 || carry != 0) {
            int d = (a&1) ^ (b&1) ^ carry;
            carry = ((a&1)&carry) | ((b&1)&carry) | ((a&1)&(b&1));
            res.append(d);
            a >>= 1;
            b >>= 1;
        }
        res.reverse();
        return Integer.parseInt(res.toString(),2);
    }
0 Answers
Related