# 231. Power of Two - CPP - Solution

• ``````//231. Power of Two
//https://leetcode.com/problems/power-of-two/
//http://www.cnblogs.com/grandyang/p/4623394.html
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
};
int main(int argc, char** argv) {
Solution solution;
getchar();
return 0;
}``````

• ``````class Solution {
public:
bool isPowerOfTwo(int n) {
if(!n || n<0)
return false;
bool flag = 0;
//int t = ceil(log2(n));
for(int i=0; i<32; ++i) {
if(n&1 == 1) {
if(!flag)
flag = true;
else
return false;
}
n >>= 1;
}
return flag;
}
};

class Solution {
public:
bool isPowerOfTwo(int n) {
if(!n)
return false;

int t = floor(log2(n));
if(pow(2, t) == n)
return true;
return false;
}
};

class Solution {
public:
bool isPowerOfTwo(int n) {
if(!n || n<0)
return false;

int t = floor(log2(n));
int b = ceil(log2(n));
if(b-t == 0)
return true;
return false;
}
};
``````

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