ProgrammingVery hardJEE Main · CAT placement

What is printed?

What is printed?
def f(n):
    c = 0
    while n:
        n &= n - 1
        c += 1
    return c
print(f(255), f(-1 & 0xFF), f(0))
  1. A. 8 7 0
  2. B. 8 8 0
  3. C. 9 8 0
  4. D. 8 8 1

Correct answer: B. 8 8 0

n &= n - 1 clears the lowest set bit on each pass, so the loop counts set bits. 255 has eight and -1 & 0xFF is also 255, while 0 never enters the loop.

More Python Programming questions

Exams that ask this topic