0ms c++ solution :)


  • 0
    Z

    Main idea: num + complement( num ) = 1111..
    Therefore, we can use "2^len - 1 - num" to get the complement.
    This code is fast, take 0ms, beats 97.15%

    class Solution {
    public:
        int findComplement(int num) {
            int len = 0;
            int tmp = num;
            while (tmp) {
                tmp >>= 1;
                ++ len;
            }
            return pow(2, len) - 1 - num;
        }
    };
    

Log in to reply
 

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