algorithm notes: leetcode#326 power of three

Problem


Solution


Initial thoughts

Python implementation

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

Java implementation

1
2
3
4
5
6
7
8
9
10
11
class {
public boolean isPowerOfThree(int n) {
if(n == 0){ return false; }
if(n == 1){ return true; }
while(n % 3 == 0){
if(n == 3){ return true; }
n /= 3;
}
return false;
}
}

Time complexity

O(log3N).

Space complexity

O(1).


326. Power of Three
(中文版) 算法笔记: 力扣#326 3的幂