您的位置:首页 > 编程语言 > Python开发

判断一个数是不是3的幂——Power of three?

2016-05-14 14:33 381 查看


Given an integer, write a function to determine if it is a power of three.

Follow up:

Could you do it without using any loop / recursion?
LINKTO  >>

Python:

solution 1:

class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 3 ** round(math.log(n,3)) == n
solution 2:



class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
if n == 0 or n % 3 > 0:
return False
return self.isPowerOfThree(n / 3)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 python algorithm