1538. Set Bits Through N
A lab technician writes every whole number from 0 up to and including n in binary on a long paper strip, then wants to know how many digits on the strip are 1. Writing them all out is hopeless when n is huge.
Given n, return the total count of 1 bits across the binary forms of 0, 1, 2, ..., n. Zero contributes nothing. For example, the numbers up to 5 are 0, 1, 10, 11, 100, 101, which hold seven ones in total.
Bit position b repeats a pattern of 2^b zeros followed by 2^b ones, so you can count each position separately without visiting every number. Aim for time proportional to the number of bits of n and constant extra space. The answer fits comfortably in a signed 64-bit integer.
Example 1
- Input:
- n = 5
- Output:
- 7
- Explanation:
Numbers 0..5 hold 0+1+1+2+1+2 = 7 ones.
Example 2
- Input:
- n = 12
- Output:
- 22
- Explanation:
Counting ones for 0..12 gives 4 for 0..3, 8 for 4..7, 8 for 8..11 and 2 for 12, so 22.
Constraints
0 ≤ n ≤ 1014 (the answer is below 253)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(log n)
- Space
- O(1)