psotirov

Dancing Bits

Dec 10th, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2.  
  3. class DancingBits
  4. {
  5.     static void Main()
  6.     {
  7.         int K = int.Parse(Console.ReadLine()); // reads the depth of the "dancng bits" sequence
  8.         int N = int.Parse(Console.ReadLine()); // reads the quantity of inspected numbers
  9.         int dancingBits = 0; // intitally we don't have dancing bits
  10.         int currentBit = 0; // the bit's queue always starts with 1, but it would be found into the firt iteration
  11.         int counter = 0; // equal bits counter
  12.  
  13.         for (int i = 0; i < N; i++)
  14.         {
  15.             int number = int.Parse(Console.ReadLine());
  16.             int binaryLength = 32;
  17.             while (((number >> (binaryLength-1)) & 1) == 0) binaryLength--; // calculates binary length of the number
  18.             for (int j = binaryLength; j > 0; j--) // walks through number's bits from most to least one
  19.             {
  20.                 int numberBit = (number >> (j - 1)) & 1;
  21.                 if (numberBit == currentBit) // checks if we have sequence of equal bits into the queue  
  22.                 {
  23.                     counter++; // if YES counts them
  24.                 }
  25.                 else
  26.                 {
  27.                     currentBit = numberBit; // if NO, selects current bit as start of new sequence
  28.                     if (counter == K) // checks if sequence of K equal bits have been reached previously
  29.                     {
  30.                         dancingBits++; // counts this Dancing Bits sequence
  31.                     }
  32.                     counter = 1; // and resets the counter
  33.                 }
  34.             }            
  35.         }
  36.         if (counter == K) dancingBits++; // takes into account the last sequence
  37.         Console.WriteLine(dancingBits);
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment