Binary Gap

Given a positive integer `n`, return the longest distance between any two adjacent 1 bits in its binary representation, or 0 if there are fewer than two 1 bits. Two 1 bits are adjacent when only 0 bits lie between them, and their distance is the difference of their bit positions. For example, in `1001` the two 1 bits are at distance 3.

30:00

Binary Gap
easy
Free written solution
Topics
Companies

Given a positive integer n, return the longest distance between any two adjacent 1 bits in its binary representation, or 0 if there are fewer than two 1 bits. Two 1 bits are adjacent when only 0 bits lie between them, and their distance is the difference of their bit positions. For example, in 1001 the two 1 bits are at distance 3.

Example 1:
Input: {"n":22}
Output: 2
Constraints:
  • 1≤n≤1091 \leq n \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":22}

n = 22

1

4

0

3

1

2

1

1

0

0

22 in binary is 10110. Read the bits from the right (position 0) and remember where the last 1 was.

▲ i = -1
▲ last = -1
best = 0
Variables
VariableValue
bit-
last-1
best0
DepthFunction Call
Stack empty
0/11