Given a positive integer N, find out how many positive integers strictly less than N have the same number of set bits as N.
Input : 8 Output :3 Explanation: Binary representation of 8 : 1000, so number of set bits in 8 is 1. So the integers less than 8 with same number of set bits are : 4, 2, 1 Input :1 Output :0 Input :4 Output :2
1. Using __builtin_popcount() inbuilt function, count set bits in N and store into a temp variable 2. Iterate from n-1 to 1 and also count set bits in i using __builtin_popcount() function 3. Now, compare temp with __builtin_popcount(i) 4. If both are equal then increment counter variable 5. Return counter
Below is the implementation of above approach.
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if a number has same number of set and unset bits
- Set all odd bits of a number
- Set all even bits of a number
- Largest number less than X having at most K set bits
- For every set bit of a number toggle bits of other
- Toggle first and last bits of a number
- Toggle all even bits of a number
- Toggle all odd bits of a number
- Check whether the number has only first and last bits set
- Set all the bits in given range of a number
- Check whether the number has only first and last bits set | Set 2
- Swap bits in a given number
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.