Check if Number is a Sum of Powers of Three - Problem
Given an integer n, determine whether it can be represented as the sum of distinct powers of three.
A power of three is any number of the form 3x where x is a non-negative integer. For example: 1 = 30, 3 = 31, 9 = 32, 27 = 33, etc.
Important: Each power of three can be used at most once in the sum.
Examples:
n = 12→truebecause12 = 9 + 3 = 32 + 31n = 91→truebecause91 = 81 + 9 + 1 = 34 + 32 + 30n = 21→falsebecause no combination of distinct powers of three sums to 21
Input & Output
example_1.py — Python
$
Input:
n = 12
›
Output:
true
💡 Note:
12 can be expressed as 9 + 3 = 3² + 3¹. In base-3: 12 = 110₃, which contains only 0s and 1s.
example_2.py — Python
$
Input:
n = 91
›
Output:
true
💡 Note:
91 = 81 + 9 + 1 = 3⁴ + 3² + 3⁰. In base-3: 91 = 10101₃, which contains only 0s and 1s.
example_3.py — Python
$
Input:
n = 21
›
Output:
false
💡 Note:
21 cannot be expressed as a sum of distinct powers of 3. In base-3: 21 = 210₃, which contains the digit 2.
Constraints
- 1 ≤ n ≤ 107
- Important: Each power of 3 can be used at most once
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Numbers that work have a special base-3 representation
2
Check Each Digit
Convert to base-3 and ensure no digit is 2 or higher
3
Mathematical Insight
Digit 2 means using a power of 3 twice, which violates the 'distinct' requirement
Key Takeaway
🎯 Key Insight: Converting to base-3 instantly reveals if a number can be expressed as a sum of distinct powers of 3 - just check that no digit is 2 or higher!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code