Java one line solution without using AND (&) or XOR (^)


  • 7
    Y

    To find complement of num = 5 which is 101 in binary.
    First ~num gives ...11111010 but we only care about the rightmost 3 bits.
    Then to erase the 1s before 010 we can add 1000

        public int findComplement(int num) {
            return ~num + (Integer.highestOneBit(num) << 1);
        }
    

  • 1

    Will range overflow happen in this solution?


  • 3
    Y

    @怒砍大Offer
    You mean when num = Integer.MAX_VALUE?
    The expected result is 0

    0111 1111 1111 1111 1111 1111 1111 1111 // num
    1000 0000 0000 0000 0000 0000 0000 0000 // ~num
    0100 0000 0000 0000 0000 0000 0000 0000 // Integer.highestOneBit(num)
    1000 0000 0000 0000 0000 0000 0000 0000 // Integer.highestOneBit(num) << 1
    

    Then adding ~num and Integer.highestOneBit(num) << 1 together should give the desired result.


  • 0
    A

    awesome solution


Log in to reply
 

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