Given a positive integer N, the task is to count the total number of set bits in binary representation of all the numbers from 1 to N.
Input: N = 3
setBits(1) + setBits(2) + setBits(3) = 1 + 1 + 2 = 4
Input: N = 6
- Base case: Number of set bits in 0 and 1 are 0 and 1 respectively.
- Now for every element i from the range [2, N], if i is even then it will have the same number of set bits as i / 2 because to get the number i we just shift the number i / 2 by one. While shifting, the number of set bits does not change.
- Similarly, if i is odd then it will have 1 additional set bit at 0th position than i – 1 which was even.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count total set bits in all numbers from 1 to n | Set 2
- Count total set bits in all numbers from 1 to n
- Count total unset bits in all the numbers from 1 to N
- Python map function | Count total set bits in all numbers from 1 to n
- Count total bits in a number
- Find the total count of numbers up to N digits in a given base B
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Count set bits in the Kth number after segregating even and odd from N natural numbers
- Check if bits of a number has count of consecutive set bits in increasing order
- Total character pairs from two strings, with equal number of set bits in their ascii value
- Print numbers having first and last bits as the only set bits
- Total number of non-decreasing numbers with n digits
- Count of sub-sets of size n with total element sum divisible by 3
- Sum of numbers with exactly 2 bits set
- Count set bits in an integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.