Data Structures & AlgorithmsHardGATE CS · competitive programming

Brian Kernighan's loop (x &= x − 1 until x is 0) counts the set bits of x. What is the total number of loop iterations when it is run once for each x from 1 to 100?

  1. A. 350
  2. B. 301
  3. C. 319
  4. D. 325

Correct answer: C. 319

Each iteration clears one set bit, so the iterations per number equal its popcount. The sum of popcounts over 1..100 is 319; 350 assumes half of seven bit positions are set for every number.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic