C# solution with XOR


  • 0
    H

    Create a mask with number of 1's and then XOR with the actual value

    public int FindComplement(int num)
            {
                int number = num;
                int mask = 1;
                // Move the 1 to left and then do a XOR
                while (0 != (num = num >> 1)) mask = (mask << 1) | 1;
                return mask ^ number;
            }
    

Log in to reply
 

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