1393. Count Total Set Bits in All Numbers 1 to N

HardBit ManipulationBit MathCountingMath

Given a positive integer n, return the total number of set bits across all integers from 1 to n inclusive.

Input: A JSON object {"n": <positive integer>}.

Output: Return the total count of 1-bits in 1, 2, ..., n.

Examples

Example 1
Input: {"n":6}
Output: 9
Explanation: The set-bit counts of 1..6 sum to 9.
Example 2
Input: {"n":1}
Output: 1
Explanation: Only the number 1 with one set bit -> 1.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →