Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
思路
- 循环除3、取余,判定是否3的幂(与题目不建议使用循环、递归的思想不符)
- math函数,求log3(n),判断是否为整数
- 转换为3进制,判断是否为10*形式的三进制数
源码
1 | //326. Power of Three |
运行结果:
21038/ 21038 test cases passed.
Status: Accepted
Runtime: 108 ms
Submitted: 0 minutes ago
You are here! Your runtime beats 82.13% of csubmissions.
总结
- 最初尝试用树根(Digit Root)理论找3的幂数规律,未找到决定性规律。
- 用math库的方式,在leetcode中是支持的。
- 循环或递归的方式可行,但时间复杂度是O(logn)。