Sponsored
Sponsored
This approach leverages the fact that if a number n
is a power of three, it should be divisible by 3 repeatedly until it becomes 1. If at any step, n
is not divisible by 3 and it's greater than 1, it cannot be a power of three.
Time Complexity: O(log n)
Space Complexity: O(1)
1public class Solution {
2 public boolean isPowerOfThree(int n) {
3 if (n < 1) return false;
4 while (n % 3 == 0) {
5 n /= 3;
6 }
7 return n == 1;
8 }
9}
Java provides similar functionality, checking if n
is a valid power of 3 using iterative division.
This approach uses logarithms to determine if a number is a power of three. By taking the logarithm of the number and comparing it to the logarithm base 3, we can check if they form an integer ratio.
Time Complexity: O(1)
Space Complexity: O(1)
1#include <cmath>
2
bool isPowerOfThree(int n) {
if (n < 1) return false;
double logRes = log10(n) / log10(3);
return (logRes - (int)logRes) == 0;
}
Similar to the C solution, this C++ function uses log base 10 to determine if the division produces an integer, indicating a power of three.