原题链接:https://leetcode.com/problems/power-of-two/
原题:Given an integer, write a function to determine if it is a power of two.
题意:给你一个整数,要你写一个函数去判断这个数是否是2的n次幂
思路:2的n次幂,它的二进制除了首位是1,其余都是0,所以只要判断它二进制是否符合条件即可。
AC代码:
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>0&&!(n&n-1));
}
};
另外看到一个思路,也是二进制,不过是数二进制中1的数目
class Solution {
public:
bool isPowerOfTwo(int n) {
int count = 0;
while (n > 0)
{
count+=(n&0x01);
n>>=1;
}
return count==1;
}
};