Java solution with bit manipulation with explanation


  • 0
    Y

    Since bit '1' is changed to '0', even the highest order of '1' bit of num is at 32nd bit, we still don't need to consider the overflow case for the result.

        public int findComplement(int num) {
                int res = 0;
                int i = 0;
                while (num != 0) {
                    if ((num & 1) == 0)
                        res ^= (1 << i);
                    num = (num >> 1);
                    i++;
                }
                return res;
        }
    

Log in to reply
 

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