题目描述:
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?
题目大意:
给定一个整数,编写函数判断它是否是3的幂。
进一步思考:
你可以不用循环/递归解出本题吗?
解题思路:
解法I:求对数,然后乘方,判断得数是否相等
Python代码:
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 3 ** round(math.log(n,3)) == n
解法II: 递归法
Python代码:
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)
本文链接:http://bookshadow.com/weblog/2016/01/08/leetcode-power-three/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。