Simple Java solution


  • 0
    P

    The idea was to create a mask that would equal the number of bits that makes up num (call this n bits).
    Once I have a mask of n 1 bits, perform XOR with original num value.

    public int findComplement(int num) {
        int mask = 0b0; // Create an empty mask, will grow with 1's
        int temp = num; // copy of num to bit shift
        
        while(temp != 0){
            temp >>= 1;
            mask = (mask << 1) | 1; // mask bits will equal num bits, (all 1's)
        }
        return mask ^ num; // XOR num with mask will give complement
    }
    

Log in to reply
 

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