LeetCode 868: Binary Gap Solution

Master LeetCode problem 868 (Binary Gap), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

868. Binary Gap

Problem Explanation

Explanation

To solve this problem, we need to convert the given integer n into its binary representation and then iterate through the binary digits to find the longest distance between any two adjacent 1's.

  1. Convert the integer n to its binary representation.
  2. Iterate through the binary representation and keep track of the distance between adjacent 1's.
  3. Update the maximum distance found so far.
  4. Return the maximum distance as the result.

Time Complexity

The time complexity of this solution is O(log n) because we need to convert the integer n into its binary representation, which requires log n bits.

Space Complexity

The space complexity of this solution is O(log n) to store the binary representation of the integer n.

Solution Code

class Solution {
    public int binaryGap(int n) {
        String binary = Integer.toBinaryString(n);
        int maxDistance = 0;
        int lastOneIndex = -1;
        
        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '1') {
                if (lastOneIndex != -1) {
                    maxDistance = Math.max(maxDistance, i - lastOneIndex);
                }
                lastOneIndex = i;
            }
        }
        
        return maxDistance;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 868 (Binary Gap)?

This page provides optimized solutions for LeetCode problem 868 (Binary Gap) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 868 (Binary Gap)?

The time complexity for LeetCode 868 (Binary Gap) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 868 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 868 in Java, C++, or Python.

Back to LeetCode Solutions