Java Solution: Find the highestOne Bit, generate the mask and XOR.

  • 0

    I believe the question requires us to find the highestOne bit without using the built-in library.

    public int findComplement(int num) 
        if(num<=0)  return 1;
        // Find the higestOne
        int highestOne=-1;
        for(int i=0;i<32;i++)
        // Generate the Mask
        int mask =  0xFFFFFFFF ^ (0xFFFFFFFF << (highestOne+1));
        // XOR the Mask
        return num ^ mask;

Log in to reply

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