> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Check if Number is a Sum of Powers of Three

> Tested Python solution for LeetCode 1780 with 48 pytest cases. Generate a practice environment with lcpy.

LeetCode 1780, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Recursion](/catalog/topics/recursion), [Backtracking](/catalog/topics/backtracking). [View on LeetCode](https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/description/).

Generate this problem as a practice environment: tested reference solution, 48 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1780   # by problem number
lcpy gen -s check_if_number_is_a_sum_of_powers_of_three   # by problem name
```

## 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 == 3^x`.

### Examples

```
Input: n = 12
Output: true
Explanation: 12 = 3^1 + 3^2
```

```
Input: n = 91
Output: true
Explanation: 91 = 3^0 + 3^2 + 3^4
```

```
Input: n = 21
Output: false
```

### Constraints

* 1 \<= n \<= 10^7

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/check_if_number_is_a_sum_of_powers_of_three/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/check_if_number_is_a_sum_of_powers_of_three/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log_3 n)
    # Space: O(1)
    def check_powers_of_three(self, n: int) -> bool:
        while n > 0:
            if n % 3 == 2:
                return False
            n //= 3
        return True
```

## Complexity

| Time | Space |
| - | - |
| O(log\_3 n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.