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?- A. 0 3 8 9
- B. 1 3 8 10
- C. 0 3 8 10
- 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
- Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum. python a = [3, 4, 5, 6] cnt = 0 for…
- Problem: Find the missing number in an array containing n distinct values from 0..n. python def missing(a): x = len(a) for i, v in…
- Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic). java static long power(long b, long e, long m) { long r = 1; b…
- Problem: Sum the remainders of a list of signed deltas modulo 3 in C++ and in Python. cpp int a = -7 % 3; int b = 7 % -3; int c = ((-7 %…
- Problem: Sum the prices of n = 100000 items, each 50000, in Java. java int n = 100000, price = 50000; int total = n price; long total2 = n…
- Problem: Count primes below n with the sieve of Eratosthenes. python def countprimes(n): if n < 3: return 0 isp = [True] n; isp[0] =…