fbinnzhivko

05.01 Game of Bits

May 5th, 2016
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4. class GameOfBits
  5. {
  6.     static void Main()
  7.     {
  8.         uint number = uint.Parse(Console.ReadLine());
  9.         string binary = Convert.ToString(number, 2);
  10.         //Console.WriteLine(binary);
  11.         binary = ReverseString(binary);
  12.  
  13.         StringBuilder temp = new StringBuilder();
  14.         string command = "";
  15.         while (command != "Game Over!")
  16.         {
  17.             command = Console.ReadLine();
  18.  
  19.             if (command == "Game Over!")
  20.             {
  21.                 //Console.WriteLine(binary);
  22.                 binary = ReverseString(binary);
  23.                 int count = binary.Count(c => c == '1');
  24.                 ulong final = BinaryToDecimal(binary);
  25.  
  26.                 Console.WriteLine("{0} -> {1}", final, count);
  27.             }
  28.  
  29.             if (command == "Odd")
  30.             {
  31.                 for (int i = 0; i < binary.Length; i++)
  32.                 {
  33.                     if (i % 2 == 0)
  34.                     {
  35.                         temp.Append(binary[i]);
  36.                     }
  37.                 }
  38.             }
  39.             else if (command == "Even")
  40.             {
  41.                 for (int i = 0; i < binary.Length; i++)
  42.                 {
  43.                     if (i % 2 != 0)
  44.                     {
  45.                         temp.Append(binary[i]);
  46.                     }
  47.                 }
  48.             }
  49.  
  50.             binary = temp.ToString();
  51.             temp.Clear();
  52.             //Console.WriteLine(binary);
  53.         }
  54.     }
  55.     private static ulong BinaryToDecimal(string number)
  56.     {
  57.         ulong decNumber = 0;
  58.         int index = 0;
  59.         for (int i = number.Length - 1; i >= 0; i--)
  60.         {
  61.             decNumber += (ulong)(int.Parse(number[i].ToString()) * Math.Pow(2, index));
  62.             index++;
  63.         }
  64.         return decNumber;
  65.     }
  66.  
  67.     private static string ReverseString(string s)
  68.     {
  69.         char[] arr = s.ToCharArray();
  70.         Array.Reverse(arr);
  71.         return new string(arr);
  72.     }
  73. }
Add Comment
Please, Sign In to add comment