Class Solution

java.lang.Object
g0801_0900.s0868_binary_gap.Solution

public class Solution extends Object
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>&rsquo;s in the binary representation of</em> <code>n</code><em>. If there are no two adjacent</em> <code>1</code><em>&rsquo;s, return</em> <code>0</code><em>.</em></p> <p>Two <code>1</code>&rsquo;s are <strong>adjacent</strong> if there are only <code>0</code>&rsquo;s separating them (possibly no <code>0</code>&rsquo;s). The <strong>distance</strong> between two <code>1</code>&rsquo;s is the absolute difference between their bit positions. For example, the two <code>1</code>&rsquo;s in <code>&quot;1001&quot;</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 &ldquo;10110&rdquo;.</p> <p>The first adjacent pair of 1&rsquo;s is &ldquo;10110&rdquo; with a distance of 2.</p> <p>The second adjacent pair of 1&rsquo;s is &ldquo;10110&rdquo; with a distance of 1.</p> <p>The answer is the largest of these two distances, which is 2.</p> <p>Note that &ldquo;10110&rdquo; is not a valid pair since there is a 1 separating the two 1&rsquo;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 &ldquo;1000&rdquo;. There are not any adjacent pairs of 1&rsquo;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 &ldquo;101&rdquo;.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= n <= 10<sup>9</sup></code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • binaryGap

      public int binaryGap(int n)