题目:
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?
思考:
能否不使用循环或递归?
方法一:性能192ms
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
if n < 3:
return False
while n % 3 == 0:
n /= 3
if n == 1:
return True
return False
方法二:性能169ms
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
#1162261467 = pow(3,19)
return n > 0 and (1162261467 % n == 0)