Check Power of 3 Explained
Problem Statement
Given an integer n, determine if it is a power of 3, i.e., if there exists an integer k such that n = 3^k. This problem tests your ability to work with number properties and avoid floating-point precision issues when checking divisibility by 3 repeatedly.
Example
Input: n = 27
Output: true
Explanation: 27 = 3^3, so it is a power of 3.
Code
Java
Python
JavaScript
public class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) return false;
while (n > 1) {
if (n % 3 != 0) return false;
n /= 3;
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isPowerOfThree(27)); // true
}
}
def is_power_of_three(n):
if n <= 0:
return False
while n > 1:
if n % 3 != 0:
return False
n //= 3
return True
# Example usage
print(is_power_of_three(27)) # True
function isPowerOfThree(n) {
if (n <= 0) return false;
while (n > 1) {
if (n % 3 !== 0) return false;
n = Math.floor(n / 3);
}
return true;
}
// Example usage
console.log(isPowerOfThree(27)); // true
Explanation
- If
nis less than or equal to 0, it cannot be a power of 3. - Repeatedly divide
nby 3 as long as it’s greater than 1. - If any division leaves a remainder,
nis not a power of 3. - If
nreduces to 1, it is a power of 3.
Note
The time complexity is O(log n) with base 3. An alternative mathematical approach uses the fact that the largest power of 3 within 32-bit integer limits (3^19 = 1162261467) can be used to check if
n divides it evenly.
