Problem
Given an integer n
, return true if it is a power of three. Otherwise, return false.
An integer n
is a power of three, if there exists an integer x
such that
Example 1:
1 | Input: n = 27 |
Example 2:
1 | Input: n = 0 |
Example 3:
1 | Input: n = 9 |
Example 4:
1 | Input: n = 45 |
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
Analysis
题目给出一个数字n
,要判断这个数是否3的x
次方。最无脑的方法就是写个循环,不断除以3,最后如果剩下1的话就说明这个数是3的x
次方。但这里我们要看看能否在不用递归或者循环的前提下,快速判断出结果。
在数学中,解决次方很常见的做法是使用对数,因为对数有个换底公式n
满足
使用换底公式,
Solution
无
Code
1 | class Solution { |
Summary
这道题目更偏向于数学知识,主要是使用对数的性质处理次方问题。同时也涉及到了C++计算过程中,判断整数、精度等问题,非常值得总结。这道题目的分享到这里,感谢你的支持!
v1.5.2