Check if Number is a Sum of Powers of Three

Given an integer n, return true if n can be written as the sum of distinct powers of three, and false otherwise. A power of three is any number of the form 3^x for an integer x >= 0.

30:00

Check if Number is a Sum of Powers of Three
medium
Free written solution
Topics
Companies

Given an integer n, return true if n can be written as the sum of distinct powers of three, and false otherwise. A power of three is any number of the form 3^x for an integer x >= 0.

Example 1:
Input: {"n":12}
Output: true
Constraints:
  • 1≤n≤1071 \leq n \leq 10^7

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":12}

Write 12 in base 3. Each power of three may be used at most once, so every base-3 digit must be 0 or 1.

n left

12

12 in base 3 (read right to left)

…?

one slot per power of three

No digits read yet.

chosen powers: none yet = 0
Variables
VariableValue
n12
DepthFunction Call
Stack empty
0/10