一.解法
https://leetcode-cn.com/problems/power-of-two/
要點(diǎn):位運(yùn)算
一開(kāi)始用C++,想法是不斷除以二直到1,同時(shí)每次取2的余數(shù),如果途中余數(shù)出現(xiàn)了1說(shuō)明不是。
后來(lái)參考題解位運(yùn)算,明白了2的冪的充要條件是n>0 && n&(n-1)==0,java和Python用了位運(yùn)算方法。
二.Python實(shí)現(xiàn)
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return (n>0) and (n&(n-1))==0
三.C++實(shí)現(xiàn)
class Solution {
public:
bool isPowerOfTwo(int n) {
int last;
if(n<=0) return false;
while(n!=1){
last=n%2;
if(last==1) return false;
n=n/2;
}
return true;
}
};
四.java實(shí)現(xiàn)
class Solution {
public boolean isPowerOfTwo(int n) {
if ((n>0) && (n&(n-1))==0) return true;
return false;
}
}