Binary Gap
Binary Gap
Bit Manipulation
Problem Statement
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.
Example
Example 1:
Input: n = 22
Output: 2
Explanation: The binary representation of 22 is 10110. The first pair of adjacent 1's has a distance of 2. The second pair has a distance of 1. The answer is the largest of these, 2.
Solution (One Pass)
We can solve this by iterating through the bits of the number while keeping track of the last position we saw a '1'.
Algorithm Steps
- Initialize
max_distance = 0
andlast_position = -1
. - Iterate through the bits of the number from 0 to 31.
- If the current bit is a '1':
- If
last_position
is not -1 (meaning we've seen a '1' before), calculate the distance from the current position to thelast_position
. - Update
max_distance
with the maximum distance found so far. - Update
last_position
to the current bit's index. - Return
max_distance
.
Binary Representation
0
0
0
1
0
1
1
0
Last '1' Position
None
Max Distance
0
Initial number: 22 (00010110)
Binary Gap Solution