我正在尝试使用 python 求一个以 3 为底的数字的对数。
问题来了:
https://leetcode.com/problems/power-of- Three/description/
我正在使用此代码:
import math
math.log(k,3)
但是,对于某些测试用例,它失败了,例如(还有更多测试用例):
math.log(243,3)
#output
4.999999999999999
math.log(59049,3)
#output
9.999999999999998
我不想使用
round()
,因为它会舍入其他不是 3 的幂的数字。
这是我正在使用的完整代码:
class Solution:
def isPowerOfThree(self, n: int) -> bool:
import math
k = abs(n)
if n<=0:
return False
return math.log(k,3) == int(math.log(k,3))
注意:我正在寻找涉及对数的解决方案。请随时询问任何澄清。
这只是典型的浮点错误。回想一下,当你写
math.log(x, 3)
时,Python 实际上是在计算类似 math.log(x) / math.log(3)
的东西,(自然)对数计算和除法都必须四舍五入到最接近的 float
。
但是如果您使用
int
而不是 float
进行数学计算,则可以保持准确性。
def is_power_of_three(n):
if n <= 0:
return False
while n > 1:
n, r = divmod(n, 3)
if r != 0:
return False
return n == 1
这会检查您是否可以将
n
除以 3(没有余数),直到结果为 1。