Skip to content

Instantly share code, notes, and snippets.

@SourceCode
Last active June 20, 2023 23:22
Show Gist options
  • Save SourceCode/533e00a0589fa9fb7b799c8afd6c99bf to your computer and use it in GitHub Desktop.
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;
}
}
}
@tobias-trazo
Copy link

tobias-trazo commented Aug 17, 2022

Solution in C# console app to return the length of longest binary gap of an integer.

Solution.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinaryGap
{
    class Solution
    {
        public int solution(int N)
        {
            int maxBinGapLength = 0, newBinGapLength = 0, count =  0;
            string binStr = Convert.ToString(N, 2);
            for (int x= 0; x < binStr.Length; x++)
            {
                if (binStr[x] == '1')
                {
                    if (count > 0) {
                        newBinGapLength = count;
                        count = 0;
                    }
                } else
                {
                    count++;
                }
                maxBinGapLength = Math.Max(maxBinGapLength, newBinGapLength);
            }
            Console.WriteLine(binStr);
            return maxBinGapLength;
        }
    }
}

Program.cs

using BinaryGap;

Solution binGap = new Solution();
Console.WriteLine(binGap.solution(20));
Console.WriteLine(binGap.solution(32));
Console.WriteLine(binGap.solution(529));

@vbebins
Copy link

vbebins commented Jun 20, 2023

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