Binary Gap
The task is to find the longest distance between any two adjacent 1’s in the binary representation of a given integer ( n ). If there are no two adjacent 1’s, we’ll return 0.
Approach
- Convert to Binary: Convert the given integer ( n ) to its binary representation.
- Initialize Variables: Initialize variables to keep track of the maximum distance and the last seen position of 1.
- Iterate through the Binary Representation: Iterate through the binary string and do the following: a. If a ‘1’ is found, calculate the distance from the last ‘1’ and update the maximum distance if this distance is larger. b. Update the last seen position of 1.
- Return Result: Return the maximum distance found.
Code
|
|
Example
- For
n = 22
, the binary representation is “10110”. The distances between adjacent 1’s are 2 and 1. So the output is2
. - For
n = 8
, the binary representation is “1000”. There are no adjacent 1’s, so the output is0
. - For
n = 5
, the binary representation is “101”. The distance between adjacent 1’s is 2, so the output is2
.
Complexity
The time complexity of this solution is ( O(\log n) ), where ( n ) is the input integer. This is due to the binary conversion and iteration over the binary representation. The space complexity is ( O(1) ) since we only use a constant amount of extra space.