题目:
Given an integer, write a function to determine if it is a power of two.
思路:
2的幂的二进制表示只有一个1,因此题目就变得很简单了。
代码:
public class Solution {
public boolean isPowerOfTwo(int n) {
//2的幂的二进制表示中只有一个1
if(n < 1){return false;}
int i, count = 0;
for(i = 0; i < 32; i++){
if((n&1) == 1){
count++;
}
if(count > 1){break;}
n = n >> 1;
}
if(count == 1){
return true;
}else{
return false;
}
}
}