Skip to content

Commit cea2095

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.9 MB (11.96%)
1 parent f4760a1 commit cea2095

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Given an integer <code>n</code>, you must transform it into <code>0</code> using the following operations any number of times:</p>
2+
3+
<ul>
4+
<li>Change the rightmost (<code>0<sup>th</sup></code>) bit in the binary representation of <code>n</code>.</li>
5+
<li>Change the <code>i<sup>th</sup></code> bit in the binary representation of <code>n</code> if the <code>(i-1)<sup>th</sup></code> bit is set to <code>1</code> and the <code>(i-2)<sup>th</sup></code> through <code>0<sup>th</sup></code> bits are set to <code>0</code>.</li>
6+
</ul>
7+
8+
<p>Return <em>the minimum number of operations to transform </em><code>n</code><em> into </em><code>0</code><em>.</em></p>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> n = 3
15+
<strong>Output:</strong> 2
16+
<strong>Explanation:</strong> The binary representation of 3 is &quot;11&quot;.
17+
&quot;<u>1</u>1&quot; -&gt; &quot;<u>0</u>1&quot; with the 2<sup>nd</sup> operation since the 0<sup>th</sup> bit is 1.
18+
&quot;0<u>1</u>&quot; -&gt; &quot;0<u>0</u>&quot; with the 1<sup>st</sup> operation.
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> n = 6
25+
<strong>Output:</strong> 4
26+
<strong>Explanation:</strong> The binary representation of 6 is &quot;110&quot;.
27+
&quot;<u>1</u>10&quot; -&gt; &quot;<u>0</u>10&quot; with the 2<sup>nd</sup> operation since the 1<sup>st</sup> bit is 1 and 0<sup>th</sup> through 0<sup>th</sup> bits are 0.
28+
&quot;01<u>0</u>&quot; -&gt; &quot;01<u>1</u>&quot; with the 1<sup>st</sup> operation.
29+
&quot;0<u>1</u>1&quot; -&gt; &quot;0<u>0</u>1&quot; with the 2<sup>nd</sup> operation since the 0<sup>th</sup> bit is 1.
30+
&quot;00<u>1</u>&quot; -&gt; &quot;00<u>0</u>&quot; with the 1<sup>st</sup> operation.
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>
38+
</ul>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution:
2+
def minimumOneBitOperations(self, n: int) -> int:
3+
result = 0
4+
while n:
5+
result ^= n
6+
n >>= 1
7+
return result

0 commit comments

Comments
 (0)