Problem Description
Given a positive integer n, find and return the longest distance between any two adjacent 1's in its binary representation. Two 1's are considered adjacent if there are only 0's (or none) between them. If there are no two adjacent 1's, return 0.
Key Insights
- Convert the integer to its binary representation without needing to store the entire string.
- Iterate over the bits, tracking the positions where you encounter a 1.
- Compute the gap between consecutive 1's and update the maximum gap.
- Utilize bitwise operations to efficiently process each bit.
Space and Time Complexity
Time Complexity: O(N) where N is the number of bits in n (typically constant, e.g., 32 bits for n <= 10^9).
Space Complexity: O(1) additional space.
Solution
We solve the problem by processing the number bit by bit using bitwise operations. As we iterate through the bits, we maintain a variable to record the position of the last seen 1. For each 1 found, if it is not the first one, we compute the distance (difference in bit positions) from the last 1 and update our maximum gap accordingly. This approach avoids converting the entire number into a string and uses constant space.