Leetcode 868: Binary Gap

grid47
grid47
Exploring patterns and algorithms
Aug 12, 2024 5 min read

Given a positive integer n, determine the maximum distance between any two adjacent 1’s in the binary representation of n. Two 1’s are adjacent if only 0’s separate them. If there are no two adjacent 1’s, return 0. The distance between two 1’s is the absolute difference in their positions when counting from the rightmost bit.
Problem
Approach
Steps
Complexity
Input: A single positive integer `n`.
Example: Input: n = 13
Constraints:
• 1 <= n <= 10^9
Output: Return the maximum distance between any two adjacent 1's in the binary representation of `n`. If there are no adjacent 1's, return 0.
Example: Output: 2
Constraints:
• The output is a single integer.
Goal: Find the longest distance between any two adjacent 1's in the binary representation of `n`.
Steps:
• Convert the number `n` into its binary representation.
• Identify the positions of all 1's in the binary string.
• Calculate the distances between consecutive 1's.
• Return the maximum distance found.
Goal: The solution must handle inputs efficiently within the given constraints.
Steps:
• 1 <= n <= 10^9
• Binary operations must be performed efficiently.
Assumptions:
• Input `n` is always a valid positive integer within the specified range.
• The binary representation of `n` has at least one 1.
Input: Input: n = 13
Explanation: Binary representation of 13 is '1101'. The distances between adjacent 1's are 2 (positions 1 and 3) and 1 (positions 3 and 4). The maximum distance is 2.

Input: Input: n = 2
Explanation: Binary representation of 2 is '10'. There are no two adjacent 1's, so the output is 0.

Input: Input: n = 21
Explanation: Binary representation of 21 is '10101'. The distances between adjacent 1's are 2 (positions 1 and 3) and 2 (positions 3 and 5). The maximum distance is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus