C language,easy to understand


  • 0

    the code ains to flip the leading zero in num ,then return ~num;

    int findComplement(int num) 
    {
        int count=1;
        while (num>>count>0)
            count++;
        num=num<<(32-count)>>(32-count);
        return(~num);
    }
    

    Explanation :
    for example :
    num is 5,so num is 00000000 00000000 00000000 00000 101;
    "32-count" meas the number of leading zero in 00000000 00000000 00000000 00000 101,in this example ,32-count==29
    so num<<(32-count) is 101 00000 00000000 00000000 00000000,
    then >>32-count ,so num is 11111111 11111111 11111111 11111 101,
    then return(~num), ~num is 00000000 00000000 00000000 00000 010 ==2


Log in to reply
 

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