Binary Gap

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them, possibly no 0's. The distance between two 1's is the absolute difference between their bit positions.

Example 1
Inputn = 22
Output2
22 in binary is "10110", and the largest distance among adjacent pairs of 1's is 2.
Example 2
Inputn = 8
Output0
8 in binary is "1000", so there are no adjacent pairs of 1's and the answer is 0.

Constraints

  • 1 <= n <= 10^9

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate