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: true
💡 Note: 91 can be represented as 81 + 9 + 1 = 3⁴ + 3² + 3⁰, which are distinct powers of three
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
Sum of Powers of Three - Greedy Approach INPUT n = 12 Integer to check Powers of 3: 3^0 1 3^1 3 3^2 9 3^3 27 Can we represent 12 as sum of distinct powers? Base 3 representation: 12 = 110 (base 3) ALGORITHM STEPS 1 While n > 0 Keep dividing by 3 2 Check remainder r = n % 3 3 If r == 2: false Need same power twice 4 If r == 0 or 1 Continue: n = n / 3 Execution Trace: n=12: 12%3=0, n=4 n=4: 4%3=1, n=1 n=1: 1%3=1, n=0 No remainder = 2 found! FINAL RESULT true Valid representation Decomposition: 12 = 9 + 3 = 3^2 + 3^1 Visual Proof: 9 3^2 + 3 3^1 = 12 All powers are distinct Key Insight: A number is expressible as sum of distinct powers of 3 if and only if its base-3 representation contains only digits 0 and 1. If any digit is 2, we would need the same power twice (not allowed). TutorialsPoint - Check if Number is a Sum of Powers of Three | Greedy Approach
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