问题:判断一个数是不是2的n次方,如2,4,8,16...等这些数都是可表示为2的乘方形式
代码如下所示:
import org.junit.Test;
public class Solution {
@Test
public void test(){
int n = 4;
if(isPowerofTwo(n))
System.out.println("true");
else
System.out.println("false");
}
public boolean isPowerofTwo(int n){
//return (n>0) && (!(n & (n-1)));
//Integer.toBinaryString(i)
//Integer.toBinaryString(n)
//boolean a = (n>0) &&(!(n & (n-1)));
// int c = n & (n-1);
// boolean d = !c;
// boolean b = (n>0) & (!(n & (n-1)))
if(n <= 0){
return false;
}
n&=n-1;
return n==0 ;
}
}
参考:
1、http://www.bubuko.com/infodetail-978751.html
2、http://blog.youkuaiyun.com/ciaoliang/article/details/46931427