0 ms C++ code without xor or not.


  • 1
    B

    Basic idea is to find the smallest power of 2 idx that is larger than the input number num, and output the difference between idx and num . For example, input 5 (101) , the smallest power of 2 (and larger than 5) is 8 (1000), the output should be 8 - 5 - 1 = 2 (010).

    class Solution {
    public:
        int findComplement(int num) {
            int idx = 2, tmp = num;
            
            while(tmp>>1) {
                tmp >>= 1;
                idx <<= 1;
            }
            
            return idx - num - 1;
        }
    };
    

Log in to reply
 

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