Game development as an Art

Sato Game Dev

Code Exercises


Binary Numbers


Source: Hacker Rank

Task

Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.

Input Format

A single integer,n.

Constraints

1 <= n <= 10^6

Output Format

Print a single base-10 integer denoting the maximum number of consecutive 1's in the binary representation of n.

Sample Input 1

5

Sample Output 1

1

Sample Input 2

13

Sample Output 2

2

Explanation

Sample Case 1:
The binary representation of 5 is 101, so the maximum number of consecutive 1's is 1.
Sample Case 2:
The binary representation of 13 is 1101, so the maximum number of consecutive 1's is 2.

My solution:
C#:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinaryNumbers
{
    class Program
    {


        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());

            //convert int to bin
            string binary = Convert.ToString(n, 2);
            int maxSeq = 0;
            int actualSeq = 0;
            for (int aux=0; aux< binary.Length; aux++)
            {
                if (binary[aux] == '1')
                {
                    actualSeq++;
                    if (actualSeq > maxSeq)
                        maxSeq = actualSeq;
                }
                else
                    actualSeq = 0;
            }
            Console.WriteLine(maxSeq);
            Console.ReadKey();
        }
    }
}