Skip to content

Instantly share code, notes, and snippets.

@SourceCode
Last active June 20, 2023 23:22
Show Gist options
  • Select an option

  • Save SourceCode/533e00a0589fa9fb7b799c8afd6c99bf to your computer and use it in GitHub Desktop.

Select an option

Save SourceCode/533e00a0589fa9fb7b799c8afd6c99bf to your computer and use it in GitHub Desktop.
Binary Gap - Codibility - C#
using System;
namespace ObjectApp1
{
class Program
{
static void Main(string[] args)
{
var S = new Solution();
Console.WriteLine(S.solution(0));
}
}
class Solution
{
public int solution(int n)
{
string bits = Convert.ToString(n, 2);
//Console.WriteLine($"Bit String: {bits}");
int longest = 0;
int curCount = 0;
for (int i = 0; i < bits.Length; i++)
{
if (bits[i] == '0')
{
if (curCount > 0) curCount++;
else curCount = 1;
} else curCount = 0;
if (curCount > longest) longest = curCount;
}
return longest;
}
}
}
@vbebins

vbebins commented Jun 20, 2023 •

Copy link
Copy Markdown

We can go for the bitwise, by this solution we can avoid the binary conversion,

Works for all test cases

public static int BinaryGapSolutionByBitwise(int N)
        {
            int maxLength = 0;
            int currCount = 0;
            bool counting = false;

            while (N > 0)
            {
                if ((N & 1) == 1)
                {
                    counting = true;
                    maxLength = Math.Max(maxLength, currCount);
                    currCount = 0;
                }
                else if (counting)
                {
                    currCount++;
                }

                N >>= 1; 
            }

            return maxLength;
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment