Codility BinaryGap Solution C#

By | November 7, 2017

Codility BinaryGap Solution C#

Find the longest sequence of zeros in binary representation of an integer.

Solution:

         
        public int GetBinaryGap(int N)
        {
            string binaryValue = Convert.ToString(N, 2);

            int longestBinaryGap = 0;
            int binaryGapLenght = 0;
            for (int i = 1; i & lt; binaryValue.Length; i++)
            {
                if (binaryValue[i - 1] == '1' && binaryValue[i] == '0')
                {
                    binaryGapLenght = 1;
                }
                else if (binaryValue[i - 1] == '0' && binaryValue[i] == '0')
                {
                    binaryGapLenght++;
                }
                else if (binaryValue[i - 1] == '0' && binaryValue[i] == '1')
                {
                    longestBinaryGap = Math.Max(longestBinaryGap, binaryGapLenght);
                }
            }

            return longestBinaryGap;
        }

By submitting this answer to codility I got 100% Marks.

Codility binary gap solution C#

Codility binary gap solution C#

 

For all the codility solutions Click here.

Leave a Reply

Your email address will not be published. Required fields are marked *