出处
http://www.programcreek.com/2014/07/leetcode-power-of-two-java/
Given an integer, write a function to determine if it is a power of two.
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n==0)
return false;
while(n%2==0)
n=n/2;
return n==1;
}
}
public boolean isPowerOfTwo(int n) {
return ((n & (n-1)) == 0 && n>0);
}
}
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n>1){
int t=n>>1;
int c=t<<1;
if(n!=c)
return false; //挺巧妙的
n=n>>1;
}
return true;
}
}