Binary Gap

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.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between the two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example :

Input: n = 22
Output: 2

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

//convert number to binary string
string binary(int n)
{
    string res = "";
    while (n > 0)
    {
        int temp = n % 2;

        res = to_string(temp+ res;
        n = n / 2;
    }
    return res;
}
int binaryGap(int n)
{
    string bString = binary(n);

    int ans = 0;
    int len = bString.size();
    int i = 0;
    while (i < len)
    {
        int count = 0;
        while (i < len && bString[i] == '0')
        {
            i++;
        }
        int j = i;
        i++;
        while (i < len && bString[i] == '0')
        {
            i++;
        }
        if (i == len)
        {
            break;
        }
        else
        {
            ans = max(ansi - j);
        }
    }
    return ans;
}

int main()
{
    int n = 22;

    cout << binaryGap(n);

    return 0;
}


No comments:

Post a Comment