Simple Java solution Without Using Library Function

  • 0

    I keep a mask (1) and a temp (num). I will use mask to flip every bit of num by XOR operation and shifting 1 to the left. I use temp to make sure to flip only the bits that are within num (shifting temp until temp is 0).

    public int findComplement(int num) {
        int temp = num;
        int mask = 1;
        while (temp != 0){
            num = num ^ mask;
            mask = mask << 1;
            temp = temp >> 1;
        return num;

Log in to reply

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