231. Power of Two
参考相似题[LeetCode]326. Power of Three
Given an integer, write a function to determine if it is a power of two.
给一个整数,写一个函数判断是否是2的幂。
思路:
- 判断是否<=0 或者>2147483647,是的话返回false
- 判断n%2 == 0,是的话n /= 2,循环进行,一旦 n%2 != 0,返回false
- 进行到最后n==1,返回true
代码如下:
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0 || n>2147483647)//2的幂最小是1 int最大为2147483647
return false;
while(n != 1){
if(n%2 != 0)
return false;
n /= 2;
}
return true;
}
};
int main()
{
Solution s;
int a =0;
cin >> a;
cout << s.isPowerOfTwo(a) << endl;
return 0;
}