Using XOR to find complement. Java.

  • 0

    Use XOR to find the complement. eg. 101 xor 111 is 010. The important step is to find the mask, which is all 1s and the length equals to num's binary representation.

    public int findComplement(int num) {
            int mask = Integer.highestOneBit(num) * 2 - 1;
            return num^mask;

Log in to reply

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