Check if Number is a Sum of Powers of Three — LeetCode 1780 Python Solution
- Problem
- #1780
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 12
- Output
- true
- Explanation
- 12 = 31 + 32
Python solution
class Solution:
def checkPowersOfThree(self, n: int) -> bool:
while n:
if n % 3 > 1:
return False
n //= 3
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log_3 n) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1780. Check if Number is a Sum of Powers of Three is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1780. Check if Number is a Sum of Powers of Three?
- LeetCode 1780. Check if Number is a Sum of Powers of Three is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1780. Check if Number is a Sum of Powers of Three?
- The Python solution on this page runs in O(\log_3 n).
- What is the space complexity of LeetCode 1780. Check if Number is a Sum of Powers of Three?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1780. Check if Number is a Sum of Powers of Three cover?
- LeetCode 1780. Check if Number is a Sum of Powers of Three is tagged Math on LeetCode.