【Leetcode】342. Power of Four
来源:互联网 发布:java 获取当前时间 编辑:程序博客网 时间:2024/04/29 08:21
方法一:
思路:递归,时间复杂度:O(lg(n)),空间复杂度:O(lg(n))。
public class Solution { public boolean isPowerOfFour(int num) { if (num <= 0) return false; if (num == 1) return true; if (num % 4 == 0) return isPowerOfFour(num / 4); else return false; }}
Runtime:2ms
方法二:
思路:
反复除以4,最终一定等于1:时间复杂度:O(lg(n)),空间复杂度:O(1)。
public class Solution { public boolean isPowerOfFour(int num) { if (num <= 0) return false; int i = num; for (; i % 4 == 0; i = i / 4); if (i == 1) return true; else return false; }}
Runtime:2ms
方法三:
思路:
4^x=n
log(4^x) = log(n)
x log(4) = log(n)
x = log(n) / log(4)一定是整数
rint():返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。
它有两个特殊的情况:1)如果参数本身是整数,则返回本身。2)如果不是数字或无穷大或正负0,则结果为其本身。
public class Solution { public boolean isPowerOfFour(int num) { double res = Math.log(num) / Math.log(4); if (Math.abs(res - Math.rint(res)) < 0.0000000001) return true; return false; }}
Runtime:4ms
方法四:
思路:
也可以用if (Math.abs(res - Math.round(res)) < 0.0000000001)判断。
不能用if (Math.abs(res - (int)res) < 0.0000000001)判断,int强制类型转换是舍去而不是求最接近的整数
public class Solution { public boolean isPowerOfFour(int num) { double res = Math.log(num) / Math.log(4); if (Math.abs(res - Math.round(res)) < 0.0000000001) return true; return false; }}
Runtime:3ms
方法五:
思路:
任何一个4的x次方一定能被int型里最大的4的x次方整除不成立(如2,8等)。
num & (num - 1)可以用来判断一个数是否为2的次方数。
更进一步说,就是二进制表示下,只有最高位是1,那么由于是2的次方数,不一定是4的次方数,比如8,所以还要其他的限定条件。
仔细观察可以发现,4的次方数的最高位的1都是计数位,那么只需与上一个数(0x55555555) <==>1010101010101010101010101010101,如果得到的数还是其本身,则可以肯定其为4的次方数。
public class Solution { public boolean isPowerOfFour(int num) { if (num <= 0) return false; if ((num & num - 1) == 0 && (num & 0x55555555) == num) return true; return false; }}
Runtime:2ms
1 0
- LeetCode *** 342. Power of Four
- LeetCode -- 342. Power of Four
- LeetCode-342. Power of Four
- LeetCode 342. Power of Four
- [leetcode] 342. Power of Four
- leetcode-342. Power of Four
- LeetCode.342. Power of Four
- LeetCode 342. Power of Four
- leetcode 342. Power of Four
- 342.[leetcode]Power of four
- leetcode 342. Power of Four
- LeetCode-342.Power of Four
- 【leetcode】342. Power of Four
- LeetCode 342. Power of Four
- LeetCode 342. Power of Four
- [Leetcode]342. Power of Four
- LeetCode 342. Power of Four
- [leetcode] 342. Power of Four
- UVa 1339
- 使用Filter过滤器实现权限访问
- 尽快处理完一切
- 中山大学计算机组成原理多周期CPU实验
- 【tensorflow1.0学习笔记003】构造神经网络与结果可视化代码
- 【Leetcode】342. Power of Four
- Android中获取短信的内容
- Android 一款十分简洁、优雅的日记APP
- Android 获取手机联系人和手机短信和一个简单的yinyue
- 关于 WEB/HTTP 调试利器 Fiddler 的一些技巧分享
- 详解Struts2拦截器机制
- USACO 2.1.2 Ordered Fractions
- 欧几里得算法--最大公约数&最小公倍数
- 这样的忙,不如天天想着玩