Can someone explain this solution ?


  • 1
    Y

    Hi

    This is the solution of the winner of the contest. I'm having trouble understanding this. Can someone explain how is this working ?

    int findComplement(int num) {
            long long limit = 2;
            long long numl = num;
            for (; limit <= numl; limit *= 2);
            long long ans = limit - 1 - numl;
            return ans;
        }
    

  • 0
    M

    The variable "limit" is the smallest power of 2 that's bigger than "num". Then subtract 1 to get a number that has the same number of digits as num, but with all 1s. E.g. num = 101 makes limit = 1000 and limit-1 = 111; num = 11010 makes limit = 100000 and limit-1 = 11111. Then subtract num from it to see the reverse effect.


Log in to reply
 

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