Advertisement
minnera

#30daysofcode #day10

Oct 8th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. //https://www.hackerrank.com/challenges/30-binary-numbers
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. class Solution
  8. {
  9.  
  10.     static void Main(String[] args)
  11.     {
  12.         int n = Convert.ToInt32(Console.ReadLine());
  13.         //string result = string.Concat("új szám", "régi szám");
  14.         string binaryNumber = toBinary(n);
  15.         Console.WriteLine(ones(binaryNumber));
  16.     }
  17.    
  18.     static string toBinary(int n)
  19.     {
  20.         string result = "";
  21.  
  22.         while (n != 0)
  23.         {
  24.             result = string.Concat((n%2), result);
  25.             n = n / 2;
  26.         }
  27.  
  28.         return result;
  29.     }
  30.  
  31.     static int ones(string binary)
  32.     {
  33.         int maxOnes = 0;
  34.         int db = 0;
  35.         for (int i = 0; i < binary.Length; i++)
  36.         {
  37.             if(binary[i] == '1')
  38.             {
  39.                 db++;
  40.             }
  41.             else
  42.             {
  43.                 if ((binary[i-1] == '1') && (maxOnes < db))
  44.                 {
  45.                     maxOnes = db;
  46.                 }
  47.                 db = 0;
  48.             }
  49.         }
  50.         if(maxOnes < db)
  51.         {
  52.             maxOnes = db;
  53.         }
  54.         return maxOnes;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement