【Leetcode】326. Power of Three
来源:互联网 发布:centos 打开80端口 编辑:程序博客网 时间:2024/06/03 19:47
方法一:
思路:递归,时间复杂度:O(lg(n)),空间复杂度:O(lg(n))。
public class Solution { public boolean isPowerOfThree(int n) { if (n <= 0) return false; if (n == 1) return true; if (n % 3 == 0) return isPowerOfThree(n / 3); else return false; }}
Runtime:18ms
方法二:
思路:反复除以3,最终一定等于1:时间复杂度:O(lg(n)),空间复杂度:O(1)。
public class Solution { public boolean isPowerOfThree(int n) { if (n <= 0) return false; int i = n; for (; i % 3 == 0; i = i / 3); if (i == 1) return true; else return false; }}
Runtime:18ms
方法三:
思路:
任何一个3的x次方一定能被int型里最大的3的x次方整除。
public class Solution { public boolean isPowerOfThree(int n) { if (n > 0 && 1162261467 % n == 0) return true; return false; }}
Runtime:17ms
方法四:
思路:
3^x=nlog(3^x) = log(n)
x log(3) = log(n)
x = log(n) / log(3)一定是整数
rint():返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。
它有两个特殊的情况:1)如果参数本身是整数,则返回本身。2)如果不是数字或无穷大或正负0,则结果为其本身。
public class Solution { public boolean isPowerOfThree(int n) { double res = Math.log(n) / Math.log(3); if (Math.abs(res - Math.rint(res)) < 0.0000000001) return true; return false; }}
Runtime:23ms
方法五:
思路:
也可以用if (Math.abs(res - Math.round(res)) < 0.0000000001)判断。不能用if (Math.abs(res - (int)res) < 0.0000000001)判断,int强制类型转换是舍去而不是求最接近的整数。
public class Solution { public boolean isPowerOfThree(int n) { double res = Math.log(n) / Math.log(3); if (Math.abs(res - Math.round(res)) < 0.0000000001) return true; return false; }}
Runtime:19ms
1 0
- [leetcode]326. Power of Three
- Leetcode 326. Power of Three
- Leetcode 326. Power of Three
- [leetcode] - 326. Power of Three
- 326. Power of Three LeetCode
- LeetCode ||326. Power of Three
- [LeetCode]326. Power of Three
- [leetcode] 326. Power of Three
- LeetCode *** 326. Power of Three
- leetcode 326. Power of Three
- 326.[LeetCode]Power Of Three
- LeetCode 326. Power of Three
- #leetcode#326. Power of Three
- Leetcode 326. Power of Three
- Leetcode 326. Power of Three
- leetcode 326. Power of Three
- LeetCode 326. Power of Three
- [leetcode] 326. Power of Three
- 解决java.lang.StackOverflowError: stack size 8MB报错问题
- chm 转 pdf
- 七层--愈见清晰明了
- Oracle之Date格式转换&日期时间间隔操作
- Linux环境下段错误产生的原因与调试
- 【Leetcode】326. Power of Three
- Android 单元测试学习
- 网页背景效果canvas-nest.js
- select into from 和 insert into select 区别
- 有关HTTP协议的详解
- libcurl post 请求
- int、bigint、smallint 和 tinyint的区别与长度的含义
- PAT A1049. Counting Ones (30)
- iOS日历控件