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.
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.
- 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
- Find the largest number smaller than integer N with maximum number of set 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 even bits of a number
- Set all odd bits of a number
- Toggle all even bits of a number
- Toggle first and last bits of a number
- Largest number less than X having at most K set bits
- Toggle all odd bits of a number
- Check whether the number has only first and last bits set | Set 2
- Toggle all the bits of a number except k-th bit.
- Change all even bits in a number to 0
- Swap bits in a given number
- Check whether the number has only first and last bits set
- Rotate bits of a number
- For every set bit of a number toggle bits of other
- Number with set bits only between L-th and R-th index
- Check if all bits of a number are set
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.