Easy C++


  • 5
    R

    Thought process is that you have to keep one number shift to left until it can no longer be shifted. At the same time, you can right shift by 1 for a number i and take the XOR, which leads to the opposite complement.

    class Solution {
    public:
        int findComplement(int num) {
            int copy = num;
            int i = 0;
    
            while(copy != 0) {
                copy >>= 1;
                num ^= (1<<i);
                i += 1;
            }
            return num;
        }
    };
    

  • 0
    A

    @randall.tom1868 if num is negative, then copy will never be 0, so while loop won't end


Log in to reply
 

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