题目描述
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
示例
输入: 1
输出: true
输入: 16
输出: true
代码一
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&(1<<30)%n==0;
}
};
1<<30表示二进制中1向右移动30为,也就是int中2的次幂最大的数,int中2的次幂最大的数对n取余数为0就证明n是2的次幂。
代码二
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&(n&(-n))==n;
}
};
利用按位与(&):二进制中两个数同一位都为1时才为1。
x&(-x)表示二进制中最右边的1。
如果是2的次幂那么x&(-x)=x。否则x<(-x)=x
代码三
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&(n&(n-1))==0;
}
};