Skip to content

Instantly share code, notes, and snippets.

@fabriziobagala
Created May 9, 2020 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabriziobagala/2f6a0709fe9dbf8b0626237ff9977562 to your computer and use it in GitHub Desktop.
Save fabriziobagala/2f6a0709fe9dbf8b0626237ff9977562 to your computer and use it in GitHub Desktop.
Find longest sequence of zeros in binary representation of an integer.
using System;
class Solution
{
public int solution(int N)
{
const int mask = 1;
var binaryGap = 0;
int? currentBinaryGap = null;
while (N > 0)
{
var bigEndian = N & mask;
if (bigEndian == 1)
{
if (currentBinaryGap > binaryGap)
{
binaryGap = currentBinaryGap.Value;
}
currentBinaryGap = 0;
}
else
{
if (currentBinaryGap != null)
{
currentBinaryGap++;
}
}
N >>= 1;
}
return binaryGap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment