public class IsPowerOf2 {
public static void main(String[] args) {
//判断一个数是否为2的整数次幂
IsPowerOf2 isPowerOf2 = new IsPowerOf2();
System.out.println(isPowerOf2.isPowerOf2(64));
System.out.println(isPowerOf2.isPowerOf2ForMethodOne(64));
System.out.println(isPowerOf2.isPowerOf2ForMethodTwo(64));
}
//普通写法,时间复杂度log(n)
private boolean isPowerOf2(int num) {
int temp = 1;
while (temp <= num) {
if (temp == num) {
return true;
}
temp = temp * 2;
}
return false;
}
private int[] transToByte(int num) {
int[] bytes = new int[32];
for (int i = 0; i < bytes.length; i++) {
if ((num & (int) (Math.pow(2, i))) != 0) {
bytes[i] = 1;
}
}
return bytes;
}
//先转成二进制数,再判断是否只包含一个1
private boolean isPowerOf2ForMethodOne(int num) {
int[] binary = transToByte(num);
if (num != 1 && binary[0] == 1) {
return false;
}
int count = 0;
for (int i = 0; i < binary.length; i++) {
if (binary[i] == 1) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
//位运算,时间复杂度为O(1)。牛逼啊
private boolean isPowerOf2ForMethodTwo(int num) {
return (num & num - 1) == 0;
}
}