Determine if an integer ( n ) is a power of three. More specifically, check if there exists an integer ( x ) such that ( 3^x = n ).
Example 1:
Example 2:
Example 3:
Example 4:
To determine if ( n ) is a power of three, we can follow these strategies:
We will implement the first method because it is more straightforward and easier to understand.
Here’s a solution using the iterative approach:
public class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isPowerOfThree(27)); // true
System.out.println(solution.isPowerOfThree(0)); // false
System.out.println(solution.isPowerOfThree(9)); // true
System.out.println(solution.isPowerOfThree(45)); // false
}
}
Time Complexity: ( O(\log_3 n) ). In the worst case, we keep dividing ( n ) by 3 until it becomes 1, which takes ( \log_3 n ) divisions.
Space Complexity: ( O(1) ). We only use a couple of variables for keeping track of ( n ) and the loop, so the space requirement is constant.
Feel free to ask any further questions or for additional clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?