-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPowerOfThree.java
More file actions
42 lines (35 loc) · 933 Bytes
/
PowerOfThree.java
File metadata and controls
42 lines (35 loc) · 933 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
package math;
/**
* Description: https://leetcode.com/problems/power-of-three
* Difficulty: Easy
*/
public class PowerOfThree {
/**
* Time complexity: O(log3 n)
* Space complexity: O(1)
*/
public boolean isPowerOfThreeViaLoop(int n) {
if (n < 1) return false;
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
/**
* Time complexity: O(log3 n)
* Space complexity: O(log3 n)
*/
public boolean isPowerOfThreeViaRecursion(int n) {
if (n < 1) return false;
if (n == 1) return true;
return n % 3 == 0 && isPowerOfThreeViaRecursion(n / 3);
}
/**
* Time complexity: O(log3 n)
* Space complexity: O(log3 n)
*/
public boolean isPowerOfThreeViaBaseConversion(int n) {
return Integer.toString(n, 3)
.matches("^10*$"); // in base 3 all powers of 3 start with 1
}
}