Check if Number is a Sum of Powers of Three - Problem

Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.

An integer y is a power of three if there exists an integer x such that y == 3x.

Note: Each power of three can be used at most once in the sum.

Input & Output

Example 1 — Basic Case
$ Input: n = 12
Output: true
💡 Note: 12 can be represented as 9 + 3, both are distinct powers of three (3² + 3¹)
Example 2 — Impossible Case
$ Input: n = 91
Output: false
💡 Note: 91 in base-3 is 10101, but this would require using some powers twice which violates the distinct constraint
Example 3 — Single Power
$ Input: n = 21
Output: false
💡 Note: 21 in base-3 is 210, contains digit 2 which means we'd need the same power twice

Constraints

  • 1 ≤ n ≤ 107

Visualization

Tap to expand
Check if Number is Sum of Powers of ThreeInputn = 12Convert to Base-312 → 110₃All digits ≤ 1 ✓12 = 1×9 + 1×3 + 0×1OutputtruePowers of 3: 1, 3, 9, 27, 81, ...9312781UsedUsedNot usedNot usedNot used12 = 9 + 3 (distinct powers of 3)
Understanding the Visualization
1
Input
Given integer n = 12
2
Process
Convert to base-3 and check digits
3
Output
Return true if valid
Key Takeaway
🎯 Key Insight: A number can be sum of distinct powers of 3 iff its base-3 representation has only 0s and 1s
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
890 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