Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
分析:
给定一个整数,判断其是否为2的幂。只要%2求余数不为0,则返回false;否则一直/2,判断最后是否为1,为1则为true
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
while(true)
{
if(n==1) return true;
if(n%2!=0) return false;
n/=2;
}
}
};