count the number of set bits in a 32 bit integer using brian kernighan s way ref https graphics stanford eduseanderbithacks htmlcountbitssetkernighan get1scount25 3 get1scount37 3 get1scount21 3 get1scount58 4 get1scount0 0 get1scount256 1 get1scount1 traceback most recent call last valueerror input must be a nonnegative integer get1scount0 8 traceback most recent call last valueerror input must be a nonnegative integer get1scount25 traceback most recent call last valueerror input must be a nonnegative integer this way we arrive at next set bit next 1 instead of looping through each bit and checking for 1s hence the loop won t run 32 times it will only run the number of 1 times count the number of set bits in a 32 bit integer using brian kernighan s way ref https graphics stanford edu seander bithacks html countbitssetkernighan get_1s_count 25 3 get_1s_count 37 3 get_1s_count 21 3 get_1s_count 58 4 get_1s_count 0 0 get_1s_count 256 1 get_1s_count 1 traceback most recent call last valueerror input must be a non negative integer get_1s_count 0 8 traceback most recent call last valueerror input must be a non negative integer get_1s_count 25 traceback most recent call last valueerror input must be a non negative integer this way we arrive at next set bit next 1 instead of looping through each bit and checking for 1s hence the loop won t run 32 times it will only run the number of 1 times
def get_1s_count(number: int) -> int:
    
    if not isinstance(number, int) or number < 0:
        raise ValueError("Input must be a non-negative integer")

    count = 0
    while number:
        
        
        
        number &= number - 1
        count += 1
    return count


if __name__ == "__main__":
    import doctest

    doctest.testmod()