leetcode[Power of Four]

本文介绍三种判断一个整数是否为4的幂的有效方法。包括使用预定义的哈希集合查找、通过数学对数计算验证以及利用二进制位操作特性检查。这些方法不仅展示了不同的编程技巧,还深入探讨了位运算和数学原理的应用。

思路类似于[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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值