Advertisement
Asinka

04. Binary Digits Count (SampleExam)

Dec 26th, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4.  
  5. class BinaryDigitsCount
  6. {
  7.     static void Main()
  8.     {
  9.         int b = int.Parse(Console.ReadLine());
  10.         int n = int.Parse(Console.ReadLine());
  11.         uint bit = 0;
  12.         uint mask = 0;
  13.  
  14.         if (b == 1 || b == 0)
  15.         {
  16.  
  17.             for (int j = 0; j < n; j++)
  18.             {
  19.  
  20.                 uint p = uint.Parse(Console.ReadLine());
  21.                 uint count1 = 0;
  22.                 uint count0 = 0;
  23.  
  24.                 for (int i = 0; i < 32; i++)
  25.                 {
  26.  
  27.                     //chacking which bits stay of positions p - 0 or 1
  28.                     mask = (uint)(1 << i);
  29.                     bit = (uint)((p & mask) >> i);
  30.  
  31.                     if (bit == 1) //counting how meny bits are 1
  32.                     {
  33.  
  34.                         count1 = count1 + 1;
  35.                     }
  36.                     else if (bit == 0 && mask < p) //counting how meny bits are 1
  37.                     {
  38.  
  39.                         count0 = count0 + 1;                
  40.                     }
  41.  
  42.                 }
  43.                 if (b == 1)
  44.                 {
  45.                     Console.WriteLine("{0}", count1);
  46.                 }
  47.                 else
  48.                 {
  49.                     Console.WriteLine("{0}", count0);
  50.                 }
  51.             }
  52.         }
  53.  
  54.  
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement