leetcode 231 Power of Two(位运算)

2023-03-12,,

Given an integer, write a function to determine if it is a power of two.

题解:一次一次除2来做的话,效率低。所以使用位运算的方法(左移一位相当于原数乘2)列出在int范围内的所有2的倍数,然后和n异或如果等于0,那么n就是它(两个数的异或为0,那么两个数就相等)。

注意:位运算的优先级比==的优先级低,要加括弧。

class Solution {
public:
bool isPowerOfTwo(int n) {
int a=;
if(n<=){
return false;
}
else{
for(int i=;i<=;i++){
if((n^a)==){
return true;
}
else{
a<<=;
}
}
return false;
}
}
};

更好的解法:一个数是2的倍数,那么它的二进制表示中只有一个1,其它都是0,所以如果n&(n-1)==0,那么n就是2的倍数(因为减1只会影响二进制表示中最靠右的1).

class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>)&&((n&(n-))==);
}
};

leetcode 231 Power of Two(位运算)的相关教程结束。

《leetcode 231 Power of Two(位运算).doc》

下载本文的Word格式文档,以方便收藏与打印。