231. Power of Two
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
题意:判断一个数是否是2的幂次方。
方法一:循环除2,直到为0。循环中模2,如果结果不等于0,表示不是2的次幂。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n>1)
{
if(n%2 != 0)
{
return false;
}
n = n/2;
}
return true;
}
};
方法二:整数n 与n-1 模运算(本质上是去掉最低位的1),如果结果不等于0,表示不是2的次幂。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
return (n &(n -1)) == 0 ;
}
};
还没有评论,来说两句吧...