Count Set Bits

Hard
0/120
Average time to solve is 15m
profile
Contributed by
59 upvotes
Asked in companies
HSBCSamsungBank Of America

Problem statement

You are given a positive integer ‘N’. Your task is to find the total number of ‘1’ in the binary representation of all the numbers from 1 to N.

Since the count of ‘1’ can be huge, you are required to return it modulo 1e9+7.

Note:
Do not print anything, just return the number of set bits in the binary representation of all integers between 1 and ‘N’.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases to run. 
Then the next ‘T’ lines represent the ‘T’ test cases.

The first line of each test case contains a single integer ‘N’.
Output Format
For each test case, return an integer that is equal to the count of set bits in all integers from 1 to n modulo 1e9+7.

Output for each test case will be printed in a new line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 10^9

Time limit: 1 second
Sample Input 1:
2
5
3
Sample Output 1:
7
4
Explanation For Sample Input 1 :
In the first test case,

DECIMAL    BINARY      SET BIT COUNT
1            01                  1
2            10                  1
3            11                  2
4            100                 1
5            101                 2
1 + 1 + 2 + 1 + 2 = 7 
Answer = 7 % 1000000007 = 7


In the second test case,

DECIMAL    BINARY      SET BIT COUNT
1            01                  1 
2            10                  1
3            11                  2
1 + 1 + 2 = 4 
Answer = 4 % 1000000007 = 4
Sample Input 2:
2
6
10
Sample Output 2:
9
17
Hint

Simply find the number of set bits in all numbers from 1 to n and return the sum.

Approaches (2)
Brute Force

The key idea is to count the number of set bits in each number from 1 to n and return the sum of all set bits.

 

The algorithm will be -

 

  • For each i from 1 to N -
    • We find the number of set bits for each i.
    • This can be done using a built-in function (for eg builtin_popcount in c++) or by simply using a loop and left shifting the number and finding if the last place is set or not.
  • Finally we store the count of set bits in  a variable called ‘count’ , take its mod and return it.
Time Complexity

O(N * log(N)), where ‘N’ is the given number.

 

For each number in 1 to N, it will take log(N) time to find the number of set bits in it. Hence the complexity is N * log(N).

Space Complexity

O(1)

 

Since we are using constant space.

Code Solution
(100% EXP penalty)
Count Set Bits
Full screen
Console