题目
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 == 3x.
解题思路
- 模3,判断是否为0,如果不是0则必须为1
- 输入最大3^19,判断是否为3^30约数
- 取log,判断是否为整数
代码
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while n % 3 == 0:
n /= 3
return n == 1
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 3**20 % n == 0
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
t = math.log(n, 3)
return math.fabs(t - round(t)) < 0.0000000001
视频讲解 YouTube<--欢迎点击订阅
视频讲解 bilibili<--欢迎点击订阅
-
Previous
LeetCode 1642 Furthest Building You Can Reach (Python) -
Next
LeetCode 63 Unique Paths II (Python)
Related Issues not found
Please contact @MaxMing0 to initialize the comment