X

DAYS

:

HOUR

:

MINS

:

SEC

Copied to Clipboard
Count Total Setbits
Medium Accuracy: 69.49% Submissions: 1602 Points: 4

You are given a number N. Find the total number of setbits in the numbers from 1 to N. 


Example 1:

Input: N = 3
Output: 4
Explaination: 
1 -> 01, 2 -> 10 and 3 -> 11. 
So total 4 setbits.

 

Example 2:

Input: N = 4
Output: 5
Explaination: 1 -> 01, 2 -> 10, 3 -> 11 
and 4 -> 100. So total 5 setbits.

 

Your Task:
You do not need to read input or print anything. Your task is to complete the function countBits() which takes N as input parameter and returns the total number of setbits upto N.

 

Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)

 

Constraints:
1 ≤ N ≤ 106  

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.


to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Count Total Setbits

Output Window