C# accepted, bit manipulation by count bits of 1


  • 1
    R
    public bool IsPowerOfTwo(int n) 
    {
        if (n <= 0) return false;
        
        int temp = n;
        int oneBitCount = 0;
        do
        {
            oneBitCount += 1 & temp;
            temp = temp >> 1;
        }
        while (temp != 0);
        
        return (oneBitCount <= 1);
    }

  • 1
    H
    bool  isPowerOfTwo(const int n) {
         if( n <= 0 )
            return 0;
         return n==((-n)&(n));
    }
    

    So easy


Log in to reply
 

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