possible solution?


  • 0
    A

    Could I count the number of digits in binary and then find the maximum binary value for that many digits and then xor that with num?


  • 0
    S

    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 ouput.

    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;
    }
    }


Log in to reply
 

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