psotirov

Binary Digits Count

Dec 10th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using System;
  2.  
  3. class BinaryDigitsCount
  4. {
  5.     static void Main()
  6.     {
  7.         uint B = uint.Parse(Console.ReadLine()); // what to look for - 0 or 1
  8.         int N = int.Parse(Console.ReadLine()); // quantity of numbers
  9.  
  10.         uint[] numbers = new uint[N];
  11.         for (int i = 0; i < N; i++) // Loop to enter  numbers
  12.         {
  13.             numbers[i] = uint.Parse(Console.ReadLine()); // reads from the console
  14.         }
  15.  
  16.         foreach (uint num in numbers) // Iterates through each element in the array
  17.         {
  18.             uint number = num; // transfers the iterator element to local variable
  19.             int count = 0; // bit's counter
  20.             int binaryLength = 32; // binary length of unsigned integer is 32 bits
  21.  
  22.             //Checking the binary length of the number (extracts leading 0's)
  23.             while ((number >> (binaryLength - 1) & 1) == 0) binaryLength--; // 31 shifts for the most meaning bit
  24.  
  25.             for (int j = 0; j < binaryLength; j++) // Loop through each bit of the current number
  26.             {
  27.                 if ((number & 1) == B) count++;
  28.                 number = number >> 1;
  29.             }
  30.             Console.WriteLine(count);
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment