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 = 12true because 12 = 9 + 3 = 32 + 31
  • n = 91true because 91 = 81 + 9 + 1 = 34 + 32 + 30
  • n = 21false because 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
Making Change with Powers of 33⁰27¢81¢3⁴✓ Can make 12¢: Use 9¢ + 3¢ coins12 in base-3: 110₃ (only 0s and 1s)✗ Cannot make 21¢21 in base-3: 210₃ (contains digit 2)Digit 2 would mean using the same coin twice!🎯 Key InsightIn base-3 representation:• Digit 0: Don't use that power of 3• Digit 1: Use that power of 3 exactly once• Digit 2: Would need that power of 3 twice (impossible!)
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!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.6K Views
Medium Frequency
~15 min Avg. Time
892 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