Skip to content

Commit 0177a2d

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.6 MB (88.25%)
1 parent 528472d commit 0177a2d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given an integer <code>n</code>, return <code>true</code> <em>if it is possible to represent </em><code>n</code><em> as the sum of distinct powers of three.</em> Otherwise, return <code>false</code>.</p>
2+
3+
<p>An integer <code>y</code> is a power of three if there exists an integer <code>x</code> such that <code>y == 3<sup>x</sup></code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> n = 12
10+
<strong>Output:</strong> true
11+
<strong>Explanation:</strong> 12 = 3<sup>1</sup> + 3<sup>2</sup>
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> n = 91
18+
<strong>Output:</strong> true
19+
<strong>Explanation:</strong> 91 = 3<sup>0</sup> + 3<sup>2</sup> + 3<sup>4</sup>
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> n = 21
26+
<strong>Output:</strong> false
27+
</pre>
28+
29+
<p>&nbsp;</p>
30+
<p><strong>Constraints:</strong></p>
31+
32+
<ul>
33+
<li><code>1 &lt;= n &lt;= 10<sup>7</sup></code></li>
34+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 2: Optimized Iterative Approach
2+
3+
# Time: O(log n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def checkPowersOfThree(self, n: int) -> bool:
8+
power = 0
9+
10+
while 3 ** power <= n:
11+
power += 1
12+
13+
while n > 0:
14+
if n >= 3 ** power:
15+
n -= 3 ** power
16+
17+
# We cannot use the same power twice
18+
if n >= 3 ** power:
19+
return False
20+
21+
power -= 1
22+
23+
# n has reached 0
24+
return True

0 commit comments

Comments
 (0)