If a number is a power of 3, we can keep dividing it by 3 until we end up with a value of 1.
class Solution {
public boolean isPowerOfThree(int n) {
if (n < 1) {
return false;
}
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
}
This algorithm works for any "Power of X" question for X = 2, 3, 4,...
- Time Complexity
- if number of bits in
int n
is capped at 32:O(1)
- if number of bits is allowed to grow:
O(log n)
- Space Complexity: O(1)
- Convert the number to base-3 representation.
- Check if it starts with
10
class Solution {
public boolean isPowerOfThree(int n) {
return Integer.toString(n, 3).matches("10*");
}
}
This algorithm works for any "Power of X" question for X = 2, 3, 4,...
- Time Complexity
- if number of bits in
int n
is capped at 32:O(1)
- if number of bits is allowed to grow:
O(log n)
since base conversion is implemented as repeated division
- if number of bits in
- Space Complexity:
O(1)
This algorithm only works since 3 is a prime number.
- 319 = 1162261467 is the biggest power of 3 less than
Integer.MAX_VALUE
. - Since 3 is a prime number, the only divisors of 319 are 30, 31, 32, ... 319, which happen to all be powers of 3.
- Return
true
ifn
is positive and1162261467
is divisible byn
class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 &&
1162261467 % n == 0;
}
}
- Time Complexity
- if number of bits in
int n
is capped at 32:O(1)
- if number of bits is allowed to grow:
O(log n)
due to the % operator
- if number of bits in
- Space Complexity:
O(1)