Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The problem is to find the previous smaller integer(greatest integer smaller than n), having (x-1) number of set bits in its binary representation.
Note: 1 <= n
Input : 8 Output : 0 (8)10 = (1000)2 is having 1 set bit. (0)10 = (0)2 is having 0 set bit and is the previous smaller. Input : 25 Output : 24
Following are the steps:
- Find the position of the rightmost set bit(considering last bit at position 1, second last bit at position 2 and so on) in the binary representation of n. Let the position be represented by pos. Refer this post.
- Turn off or unset the bit at position pos. Refer this post.
Previous smaller integer = 24
This article is contributed by Ayush Jauhari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Closest (or Next) smaller and greater numbers with same number of set bits
- Next greater integer having one more number of set bits
- Count set bits in an integer
- How to swap two bits in a given integer?
- Count set bits in an integer using Lookup Table
- Check if bits of a number has count of consecutive set bits in increasing order
- Previous number same as 1's complement
- Binary representation of previous number
- 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
- Same Number Of Set Bits As N
- Set all odd bits of a number
- Set all even bits of a number
- Check whether the number has only first and last bits set | Set 2
Improved By : jit_t