Given a number n, count number of integers smaller than or equal to n that have odd number of set bits.
Input : 5 Output : 3 Explanation : Integers with odd number of set bits in range 1 to 5 : 0 contains 0 set bits 1 contains 1 set bits 2 contains 1 set bits 3 contains 2 set bits 4 contains 1 set bits 5 contains 2 set bits Input : 10 Output : 5 Explanation : Integers with odd set bits are 1, 2, 4, 7 and 8.
Prerequisites : Count number of set bits
The idea is based on below fact.
If n is odd then there are total n+1 integers smaller than or equal to n (0, 1, 2 … n) and half of these integers contain odd number of set bits.
How to handle case when n is even? We know result for n-1. We count set bits in n and add 1 to n/2 if the count is odd. Else we return n/2.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Number of mismatching bits in the binary representation of two integers
- Check if bits of a number has count of consecutive set bits in increasing order
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Find the largest number smaller than integer N with maximum number of set bits
- Find a number which give minimum sum when XOR with every number of array of integers
- Check if a number has same number of set and unset bits
- Toggle bits of a number except first and last bits
- Minimum number using set bits of a given number
- M-th smallest number having k number of set bits.
- Next higher number with same number of set bits
- Set all even bits of a number
- Same Number Of Set Bits As N
- Set all odd bits of a number
- Toggle all even bits of a number
- Toggle first and last bits of a number
- Set all the bits in given range of a number
- Toggle all the bits of a number except k-th bit.
- Rotate bits of a number
- Check if all bits of a number are set
- Check whether the number has only first and last bits set | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.