Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
思路: 题越来越zz了。
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<1:
return False
elif n==1:
return True
while n>1:
if n%3!=0:
return False
n = n/3
return True
还有用math.log()做的floor()是向下取整。
import math
class Solution(object):
def isPowerOfThree(self, n):
if n <= 0:
return False
logged = math.log(n, 3)
return 3 ** math.floor(logged) == n or 3 ** math.ceil(logged) == n

本文介绍了一种方法来确定一个给定的整数是否可以表示为3的幂次方。通过使用循环除法和数学对数函数,我们提供了两种不同的Python实现方案。第一种方法通过不断除以3并检查余数来判断,第二种方法利用了math.log()函数计算对数并比较其向下和向上取整后的结果。
809

被折叠的 条评论
为什么被折叠?



