Sharing my 8ms C++ solution


  • 0
    T
    class Solution {
    private:
        int hammingWeight(uint32_t n) {
            int result = 0;
            unsigned int i, temp=1;
            for(i=0; i<32; i++)
            {
                if((n & temp) == temp)
                    result++;
                temp = temp << 1;
            }
            
            return result;
        };
        
    public:
        bool isPowerOfTwo(int n) {
            if(n<=0)
                return false;
                
            return (hammingWeight(n) == 1);
        }
    };

Log in to reply
 

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