326 Power of Three
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 n == 3^x
.
Example 1:
Example 2:
Example 3:
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
这题不难,用循环直接除就是了。因为3的n次方的数,只能有3这个因数。如果除出来的数字不是1的话,那么就不是3的次方了。譬如,27 = 3 * 3 * 3。但12 = 3 * 4。这里,T:O(log3N), S: O(1)。这里follow up的解法是数学解法。因为n的范围是正整数,然后3是质数。在正整数范围内最大的3的n次方是19。所以如果n能被3的19次方整除,那么n就是3的power。
Last updated