
Problem
Solution
Submissions
Power of Three
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to determine if an integer is a power of three. An integer is a power of three if there exists an integer x such that n = 3^x.
Example 1
- Input: n = 27
- Output: true
- Explanation:
- Step 1: 27 can be expressed as 3^3.
- Step 2: 3^3 = 3 * 3 * 3 = 27
- Step 3: Therefore, 27 is a power of three.
Example 2
- Input: n = 45
- Output: false
- Explanation:
- Step 1: 45 cannot be expressed as 3^x for any integer x.
- Step 2: The closest powers of three are 3^3 = 27 and 3^4 = 81.
- Step 3: Since 45 falls between these two powers, it is not a power of three.
Constraints
- -2^31 ≤ n ≤ 2^31 - 1
- Time Complexity: O(log n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Check if n is positive, as powers of three must be positive
- Repeatedly divide n by 3 and check if the remainder is 0
- If at any point the remainder is not 0, n is not a power of three
- If we can divide n by 3 until we get 1, then n is a power of three
- Alternatively, use a mathematical property: the largest power of 3 in the integer range is 3^19