Count set bits in an integer
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’.
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
CodingNinjas
author
2y
A simple method would be to Loop through all bits in an integer, check if a bit is set and if it is, then increment the set bit count.
Time Complexity: Θ(logn)
Auxiliary Space: O(1)
Efficient approach w...read more
CodingNinjas
author
2y
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...read more
CodingNinjas
author
2y
Optimised approach
Let us take the following example:
Let N = 7;
Then ,
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6= 0110
7 = 0111
Observe the last the bits get flipped after (2^0 = 1)
The second las...read more
Add answer anonymously...
Top Snapdeal Business Analyst interview questions & answers
Popular interview questions of Business Analyst
Top HR questions asked in Snapdeal Business Analyst
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app