Count set bits to n
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.
Implement
count_set_bits_range(n: int) → intExamples
in
[5]out7What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 30 min
solution.py
InputExpectedGot
[5]7not run yetsample