Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants.

Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants.
static int popc(int x) { return Integer.bitCount(x); }
// popc(0) + " " + popc(7) + " " + popc(255) + " " + popc(1023)
What does the commented expression evaluate to?
  1. A. 0 3 8 9
  2. B. 1 3 8 10
  3. C. 0 3 8 10
  4. D. 0 7 255 1023

Correct answer: C. 0 3 8 10

Integer.bitCount returns the number of 1 bits: 7 = 111 (3), 255 = 2⁸ − 1 (8), 1023 = 2¹⁰ − 1 (10). 2^k − 1 always has k ones. Hardware popcount is O(1); Kernighan's loop runs once per set bit.

More Coding Interview Problems questions

Exams that ask this topic