Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
给一个int数,判断是否是2的幂,这里用归纳法先拿几个数:1,2,4,8找规律,发现转换成2进制后只有1个1。
比如2:n&(n-1)就是:0010&0001,位与只有在都是1时出1,因此结果是0,返回true
class Solution {
public:
bool isPowerOfTwo(int n) {
//1 0001
//2 0010
//4 0100
//8 1000
if(n<=0)return false;
return((n&(n-1))==0);
}
};