思路类似于[Power of Three]
这里对于用3^19 % num == 0来判断不适用,这种只适用于判断一个数是否为n的幂(n为质数)
举个范例,4^15 % 2等于0,但是2不是4的幂,原因就在于4不是质数
解法一:
public class Solution { public boolean isPowerOfFour(int num) { HashSet<Integer> set = new HashSet<>(Arrays.asList(1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456,1073741824)); return set.contains(num); } }解法二:
public class Solution { public boolean isPowerOfFour(int num) { if(num <= 0) return false;//非正数单独处理,因为用对数算log(n),n必须大于0 //这里如果是4的幂,那么一定是2的幂,不会有log2(num)不会有小数产生 //直接用差值是否>0来判断即可,不用考虑误差的0.0000...1 if(Math.abs(Math.log(num) / Math.log(4) - Math.ceil(Math.log(num) / Math.log(4))) > 0){ return false; } else{ return true; } } }解法三:
public class Solution { public boolean isPowerOfFour(int num) { //1 0 //4 100 //16 10000 //64 1000000 //观察规律可知,可以用二进制来处理(与数据有关的多半想到二进制,位运算来解决) //First, Any number passes "n & (n-1)==0" must be powers of 2. //Second, all numbers above could be further categorized to 2 class. //A: all numbers that are 2^(2k+1) and B: all numbers that 2^(2k). //Third, we could show that 2^(2k+1)-1 could not pass the test of (n-1)%3==0.(证明见下一行) // 4^(n+1) - 1 = 4*4^n -1 = 3*4^n + 4^n-1. //The first is divided by 3, the second is proven by induction hypothesis //So all A are ruled out, leaving only B, which is power of 4. return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; } }