Skip to contentKEEP THE CRAFTTHE SANCTUARY

Count Set Bits

Count the 1 bits of a nonnegative integer by clearing the lowest set bit until nothing is left.

The problem

Implement count_set_bits(value). value is a nonnegative integer, and it may be wider than 32 bits. Return how many 1 bits its binary form has, without using bin or int.bit_count. For example, 45 is 101101 in binary, so count_set_bits(45) returns 4, and count_set_bits(0) returns 0.

Starter code

def count_set_bits(value):
    pass

Public examples

  1. value = 45gives4
  2. value = 64gives1
  3. value = 257gives2

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.