Skip to content

ORIGINAL CODING QUESTION

Total binary set-bit marks

Add the number of one bits in the binary representation of every integer from 0 through x, inclusive.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

One nonnegative integer x.

Constraints

0 ≤ x ≤ 100000.

Example 1

Input

3

Output

4

Counts for 0,1,2,3 are 0,1,1,2; total 4.

Example 2

Input

0

Output

0

Zero has no one bits.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

The bit count of i relates to that of floor(i/2).

Hint 2

The low bit contributes i mod 2.

Hint 3

Accumulate these counts for the full range.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →