Skip to content

Commit 0c39294

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 19.4 MB (54.01%)
1 parent 2e10927 commit 0c39294

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

  • LeetCode/1520-number-of-steps-to-reduce-a-number-in-binary-representation-to-one
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<p>Given the binary representation of an integer as a string <code>s</code>, return <em>the number of steps to reduce it to </em><code>1</code><em> under the following rules</em>:</p>
2+
3+
<ul>
4+
<li>
5+
<p>If the current number is even, you have to divide it by <code>2</code>.</p>
6+
</li>
7+
<li>
8+
<p>If the current number is odd, you have to add <code>1</code> to it.</p>
9+
</li>
10+
</ul>
11+
12+
<p>It is guaranteed that you can always reach one for all test cases.</p>
13+
14+
<p>&nbsp;</p>
15+
<p><strong class="example">Example 1:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> s = &quot;1101&quot;
19+
<strong>Output:</strong> 6
20+
<strong>Explanation:</strong> &quot;1101&quot; corressponds to number 13 in their decimal representation.
21+
Step 1) 13 is odd, add 1 and obtain 14.&nbsp;
22+
Step 2) 14 is even, divide by 2 and obtain 7.
23+
Step 3) 7 is odd, add 1 and obtain 8.
24+
Step 4) 8 is even, divide by 2 and obtain 4.&nbsp;
25+
Step 5) 4 is even, divide by 2 and obtain 2.&nbsp;
26+
Step 6) 2 is even, divide by 2 and obtain 1.&nbsp;
27+
</pre>
28+
29+
<p><strong class="example">Example 2:</strong></p>
30+
31+
<pre>
32+
<strong>Input:</strong> s = &quot;10&quot;
33+
<strong>Output:</strong> 1
34+
<strong>Explanation:</strong> &quot;10&quot; corresponds to number 2 in their decimal representation.
35+
Step 1) 2 is even, divide by 2 and obtain 1.&nbsp;
36+
</pre>
37+
38+
<p><strong class="example">Example 3:</strong></p>
39+
40+
<pre>
41+
<strong>Input:</strong> s = &quot;1&quot;
42+
<strong>Output:</strong> 0
43+
</pre>
44+
45+
<p>&nbsp;</p>
46+
<p><strong>Constraints:</strong></p>
47+
48+
<ul>
49+
<li><code>1 &lt;= s.length&nbsp;&lt;= 500</code></li>
50+
<li><code>s</code> consists of characters &#39;0&#39; or &#39;1&#39;</li>
51+
<li><code>s[0] == &#39;1&#39;</code></li>
52+
</ul>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def numSteps(self, s: str) -> int:
3+
ans = 0
4+
n = int(s, 2)
5+
while n > 1:
6+
if n & 1:
7+
n += 1
8+
else:
9+
n >>= 1
10+
ans += 1
11+
return ans

0 commit comments

Comments
 (0)