My c++ solution by bitwise operation


  • 0
    A
    class Solution {
    public:
    bool isPowerOfTwo(int n) {
        if(n<1) return false;
        while(!(n&0x1)){
            n=n>>1;
        }
        if((n|0x0) == 0x1){
            return true;
        }else{
            return false;
        }
    }
    };

  • 0
    W

    My Solution is

    bool isPowerOfTwo(int n) {
        if(n < 1) return false;
        bitset<32> s(n);
        return s.count() == 1;
    }

Log in to reply
 

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