Java solution bitwise with explanation

  • 0
        public int findComplement(int num) {
           //go to a higher number and do -1 from it to get everything as 1.
            int allones = (int)(Math.log10(Integer.highestOneBit(num))/Math.log10(2));
            allones = (1<<(allones+1))-1;
           //xor with the number to flip the bits.
            return num^allones;

Log in to reply

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