Count set bits to n

Write codeHard30 min

Your task

Return the total number of set bits (1-bits) across the binary representations of all integers from 0 to n inclusive, for n up to 10^9. Iterating each number and calling popcount is too slow; instead count bit position by bit position. For bit position i, the i-th bit cycles with period 2^(i+1): it is 0 for the first 2^i numbers and 1 for the next 2^i. Sum the contributions. Return 0 for n < 0.

Examples

count_set_bits_range(n: int) -> int
Example 1
Inputcount_set_bits_range(5)
Output7