解题思路:如果一个数是否是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/
版权声明:本文为博主原创文章,未经博主允许不得转载。