【数学】力扣326:3 的幂
给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 $ n = 3^{x}$ 。
示例:
输入:n = 27
输出:true
用到的函数:
math.log()
import math
math.log(x[, base])
默认base为自然对数e
2. round(x [, n])
返回浮点数x的四舍五入值
方法1:暴力解法
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 1 and n % 3 == 0:
n //= 3
return n == 1
时间复杂度:O(logn)。当 n 是 3 的幂时,需要除以 3 的次数为 $ log_{3}n = O(logn) $;当 n 不是 3 的幂时,需要除以 3 的次数小于该值。
空间复杂度:O(1)。
方法2:取巧
思路1:利用对数。设 $ log_{3}n = x $,如果 n 是 3 的整数次方,那么 x 一定是大于 0 的整数。
import math
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and math.log(n, 3) % 1 == 0
因为math.log()精度问题,n == 243 时通过不了。。。
可以使用round
函数解决:
import math
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and n == 3 ** round(math.log(n, 3))
思路2:因为在 int 范围内 3 的最大次方是 $ 3 ^ {19} = 1162261467 $,如果 n 是 3 的整数次方,那么 1162261467 除以 n 的余数一定是零;反之亦然。
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 1162261467 % n == 0
时间复杂度:O(1)。
空间复杂度:O(1)。