@tuanledang1120

I am also tried similar approach but mine is failing. Any insights will be welcome.

I am trying the same but somehow, in the end, the result comes out to be the mask. E.g. I take num =5 i.e. 101. The mask becomes 111. The XOR(num^mask) should return 010 but I am getting 111 as the output.

public class Solution {

public int findComplement(int num) {

int mask =0;

int ans = 0;

if (num==0){

ans = 1;

}

int bits = 0;

while(num!=0){

bits++;

num = num>>>1;

}

while(bits>0){

mask = mask<<1;

mask+=1;

bits--;

}

return num ^ mask;

}

}