Package g0801_0900.s0868_binary_gap
Class Solution
java.lang.Object
g0801_0900.s0868_binary_gap.Solution
868 - Binary Gap.<p>Easy</p>
<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>’s in the binary representation of</em> <code>n</code><em>. If there are no two adjacent</em> <code>1</code><em>’s, return</em> <code>0</code><em>.</em></p>
<p>Two <code>1</code>’s are <strong>adjacent</strong> if there are only <code>0</code>’s separating them (possibly no <code>0</code>’s). The <strong>distance</strong> between two <code>1</code>’s is the absolute difference between their bit positions. For example, the two <code>1</code>’s in <code>"1001"</code> have a distance of 3.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> n = 22</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong> 22 in binary is “10110”.</p>
<p>The first adjacent pair of 1’s is “10110” with a distance of 2.</p>
<p>The second adjacent pair of 1’s is “10110” with a distance of 1.</p>
<p>The answer is the largest of these two distances, which is 2.</p>
<p>Note that “10110” is not a valid pair since there is a 1 separating the two 1’s underlined.</p>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> n = 8</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong> 8 in binary is “1000”. There are not any adjacent pairs of 1’s in the binary representation of 8, so we return 0.</p>
<p><strong>Example 3:</strong></p>
<p><strong>Input:</strong> n = 5</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong> 5 in binary is “101”.</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
binaryGap
public int binaryGap(int n)
-