Advertisement
dimipan80

ExamTask_Problem 4 – Binary Digits Count

Apr 5th, 2014
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. using System;
  2.  
  3. class BinaryDigitsCount
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         byte bitGivenValue = byte.Parse(Console.ReadLine());
  8.         ushort numN = ushort.Parse(Console.ReadLine());
  9.        
  10.  
  11.         uint [] integers = new uint [numN];
  12.         for (int i = 0; i < integers.Length; i++)
  13.         {
  14.             integers[i] = uint.Parse(Console.ReadLine());
  15.         }
  16.        
  17.        
  18.         for (int i = 0; i < integers.Length; i++)
  19.         {
  20.             uint number = integers[i];
  21.             uint countBitsCoin = CountValueOfBitsInPositiveInteger(number, bitGivenValue);
  22.             integers[i] = countBitsCoin;
  23.         }
  24.        
  25.         foreach (var item in integers)
  26.         {
  27.             Console.WriteLine(item);
  28.         }
  29.     }
  30.  
  31.     static uint CountValueOfBitsInPositiveInteger (uint number, byte bitsGivenValue)
  32.     {
  33.         uint countBits = 0;
  34.         uint quotient = 0;
  35.         byte remainder = 0;
  36.         checked
  37.         {
  38.             do
  39.             {
  40.                 quotient = number / 2;
  41.                 remainder = (byte)(number % 2);
  42.                 if (remainder == bitsGivenValue)
  43.                 {
  44.                     countBits++;
  45.                 }
  46.                 number = quotient;
  47.             } while (number > 0);
  48.         }
  49.         return countBits;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement