解題思路:如果一個數是否是2的次方,即如果其對應的二進制數1的個數如果超過1,不是的2的次方,反之纔是。
Java代碼實現:
public class Solution {
public boolean isPowerOfTwo(int n) {
int count=0;
if(n==1) return true;
if(n<=0) return false;
while(n>0){
int mod=n%2;
if(mod==1) count++;
if(count>1) return false;
n=n/2;
}
return true;
}
}
原題題目:https://leetcode.com/problems/power-of-two/