Power of Three
EASYDescription
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3x.
Example 1:
Input: n = 27 Output: true Explanation: 27 = 33
Example 2:
Input: n = 0 Output: false Explanation: There is no x where 3x = 0.
Example 3:
Input: n = -1 Output: false Explanation: There is no x where 3x = (-1).
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
Approaches
Checkout 4 different approaches to solve Power of Three. Click on different approaches to view the approach and algorithm in detail.
Recursive Division
This approach uses recursion to repeatedly check if the number can be divided by 3. The logic is broken down into base cases: a number is a power of three if, after being divided by 3 some number of times, it becomes 1. If at any point it's not divisible by 3 (and is not 1), it's not a power of three.
Algorithm
- If
n <= 0, it cannot be a power of three, so returnfalse. - If
n == 1, it is3^0, which is a power of three, so returntrue. - If
nis not divisible by 3 (n % 3 != 0), it cannot be a power of three (unless it's 1, which is already handled), so returnfalse. - If none of the above, the number is a positive multiple of 3. Make a recursive call with
n / 3and return its result.
The function isPowerOfThree is defined recursively. It first handles the base cases. Any number less than or equal to 0 cannot be a power of three. The number 1 is the base case for a successful path (3^0 = 1). If the current number n is not divisible by 3, it breaks the chain of powers of three, so we return false. Otherwise, the function calls itself with the argument n / 3, continuing the process until a base case is met.
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
if (n % 3 != 0) {
return false;
}
return isPowerOfThree(n / 3);
}
}
Complexity Analysis
Pros and Cons
- The code can be seen as an elegant and direct translation of the mathematical definition.
- It avoids explicit loop constructs.
- Less space-efficient than the iterative approach due to the recursion call stack.
- Can lead to a
StackOverflowErrorfor inputs larger than the standard integer types, although this is not an issue with the given constraints.
Code Solutions
Checking out 4 solutions in different languages for Power of Three. Click on different languages to view the code.
class Solution {
public
boolean isPowerOfThree(int n) { return n > 0 && 1162261467 % n == 0; }
}
Video Solution
Watch the video walkthrough for Power of Three
Similar Questions
5 related questions you might find useful
Patterns:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.