Power of Three - Problem

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 == 3^x.

Input & Output

Example 1 — Perfect Power of Three
$ Input: n = 27
Output: true
💡 Note: 27 = 3³, so it is a power of three
Example 2 — Not a Power of Three
$ Input: n = 0
Output: false
💡 Note: 0 is not a power of three (powers of 3 are positive)
Example 3 — Base Case
$ Input: n = 1
Output: true
💡 Note: 1 = 3⁰, so it is a power of three

Constraints

  • -2³¹ ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Power of Three - Integer Limitation Method INPUT n = 27 Integer Input Powers of 3: 3^0 = 1 3^1 = 3 3^2 = 9 3^3 = 27 Our n! Is 27 a power of 3? 27 = 3^x for some x? Max 32-bit: 3^19 = 1162261467 Max 64-bit: 3^39 ALGORITHM STEPS 1 Find Max Power 3^19 = 1162261467 (32-bit) 2 Check n > 0 27 > 0? Yes, continue 3 Divisibility Check 1162261467 % 27 == 0? 1162261467 / 27 = 43046721 1162261467 % 27 = 0 4 Return Result Remainder is 0, so TRUE return n > 0 && 1162261467 % n == 0; FINAL RESULT TRUE 27 is a power of 3 Verification: 3 x 3 x 3 = 27 3^3 = 27 OK - Confirmed! Why This Works: 3^19 contains only 3 as prime factor. Any power of 3 divides it evenly! Output: true Key Insight: The Integer Limitation method uses the largest power of 3 within the integer range (3^19 for 32-bit). Since this number's only prime factor is 3, any power of 3 will divide it evenly with no remainder. Time Complexity: O(1) - No loops needed! Space Complexity: O(1) - Constant space. TutorialsPoint - Power of Three | Integer Limitation Method
Asked in
Google 15 Apple 8 Microsoft 12
180.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen