really easy to understand C++


  • 0
    C
    int findComplement(int num) {
        bool started = false; // track if leading zeros have all been skipped or not 
        for(int i = 31; i >= 0; i--) {
            if(num & (1 << i)) {
                started = true;
                num ^= (1 << i);
            } else if(started) { // flip 0 only when it is not among leading zeros
                num |= (1 << i);
            }
        }
        return num;
    }

Log in to reply
 

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