#868

Binary Gap

newbie · 295 · lc easy +20 · verified · 74.2% accepted · 973 likes · top 85%

Description

Given a positive integer n, find and return the longest distance between any two consecutive 1-bits in the binary representation of n. If there are fewer than two 1-bits, return 0.

Two 1-bits are consecutive if no other 1-bit separates them (there may be any number of 0-bits between them). The distance between two bits is the absolute difference of their positions. For example, the two 1s in "1001" are distance 3 apart.

Example 1:

Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.

Example 2:

Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.

Example 3:

Input: n = 5
Output: 2
Explanation: 5 in binary is "101".

Code

1
2
3