Problem Statement
leetcode problem link
Brute Force [Accepted]
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
if 0 <= n < 1:
return False
return self.isPowerOfThree(n / 3)
Other Approach [Accepted]
import math
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
val = math.log10(n) / math.log10(3)
str_val = str(val)
res = str_val.split('.')[1]
return '0' == res
Editorial
Approach 1: Loop Iteration
public class Solution {
public boolean isPowerOfThree(int n) {
if (n < 1) {
return false;
}
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
}
Approach 2: Base Conversion
public class Solution {
public boolean isPowerOfThree(int n) {
return Integer.toString(n, 3).matches("^10*$");
}
}
Approach 3: Mathematics
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
}
}
Approach 4: Integer Limitations
public class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
}