-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path326.py
More file actions
58 lines (45 loc) · 980 Bytes
/
Copy path326.py
File metadata and controls
58 lines (45 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'''
326. Power of Three
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
Follow up:
Could you do it without using any loop / recursion?
'''
##Solution-1 Loop
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
elif n == 1: return True
else:
while n % 3 == 0:
n//=3
if n == 1: return True
else: return False
##Solution-2 Recursion
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
elif n == 1: return True
else:
if n%3 == 0:
return self.isPowerOfThree(n//3)
return False