Skip to content

Commit 4aac076

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 18 MB (10.92%)
1 parent f73a017 commit 4aac076

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>Given a positive integer <code>n</code>, find and return <em>the <strong>longest distance</strong> between any two <strong>adjacent</strong> </em><code>1</code><em>&#39;s in the binary representation of </em><code>n</code><em>. If there are no two adjacent </em><code>1</code><em>&#39;s, return </em><code>0</code><em>.</em></p>
2+
3+
<p>Two <code>1</code>&#39;s are <strong>adjacent</strong> if there are only <code>0</code>&#39;s separating them (possibly no <code>0</code>&#39;s). The <b>distance</b> between two <code>1</code>&#39;s is the absolute difference between their bit positions. For example, the two <code>1</code>&#39;s in <code>&quot;1001&quot;</code> have a distance of 3.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> n = 22
10+
<strong>Output:</strong> 2
11+
<strong>Explanation:</strong> 22 in binary is &quot;10110&quot;.
12+
The first adjacent pair of 1&#39;s is &quot;<u>1</u>0<u>1</u>10&quot; with a distance of 2.
13+
The second adjacent pair of 1&#39;s is &quot;10<u>11</u>0&quot; with a distance of 1.
14+
The answer is the largest of these two distances, which is 2.
15+
Note that &quot;<u>1</u>01<u>1</u>0&quot; is not a valid pair since there is a 1 separating the two 1&#39;s underlined.
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> n = 8
22+
<strong>Output:</strong> 0
23+
<strong>Explanation:</strong> 8 in binary is &quot;1000&quot;.
24+
There are not any adjacent pairs of 1&#39;s in the binary representation of 8, so we return 0.
25+
</pre>
26+
27+
<p><strong class="example">Example 3:</strong></p>
28+
29+
<pre>
30+
<strong>Input:</strong> n = 5
31+
<strong>Output:</strong> 2
32+
<strong>Explanation:</strong> 5 in binary is &quot;101&quot;.
33+
</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>
40+
</ul>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def binaryGap(self, n: int) -> int:
3+
result, last, current = 0, float('inf'), 0
4+
while n:
5+
if n & 1:
6+
result = max(result, current - last)
7+
last = current
8+
current += 1
9+
n >>= 1
10+
return result

0 commit comments

Comments
 (0)