Help me explain my code, it just somehow works!!!


  • 0
    A
    int getSum(int a, int b) {
        while (b) {
            int lb = b & (-b);
            b &= (~lb);
            while (a & lb) {
                a &= (~lb);
                lb <<= 1;
            }
            a |= lb;
        }
        return a;
    }
    

    I am writing for positive a and b, but I just found it worked somehow even for negative cases ! The basic idea is to find lowbit in b.


  • 0
    M

    @aimboy The way that we add numbers in complemental code no matter positive or negative is just the same. Maybe you need to learn about complemental code.


Log in to reply
 

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