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?

思路

如果单纯利用循环,其实还是很好做的。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if (n <= 0):
return False
while (n > 1):
if (n % 3 != 0):
return False
n = n / 3
return True

但是不利用循环的方法实在是想不出来……就看看这篇参考资料吧:

https://discuss.leetcode.com/topic/33536/a-summary-of-all-solutions-new-method-included-at-15-30pm-jan-8th