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 email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the largest number smaller than integer N with maximum number of set bits
- Next greater integer having one more number of set bits
- Largest number less than X having at most K set bits
- Print numbers having first and last bits as the only set bits
- Closest (or Next) smaller and greater numbers with same number of set bits
- Check if bits of a number has count of consecutive set bits in increasing order
- M-th smallest number having k number of set bits.
- Toggle bits of a number except first and last bits
- Count set bits in an integer
- Count set bits in an integer using Lookup Table
- Minimum integer with at most K bits set such that their bitwise AND with N is maximum
- Count of divisors having more set bits than quotient on dividing N
- Check if all bits can be made same by flipping two consecutive bits
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Increment a number by one by manipulating the bits
- How to swap two bits in a given integer?
- Binary representation of previous number
- Previous number same as 1's complement
- Cyclic shifts of integer N by another integer m
- Print numbers in the range 1 to n having bits in alternate pattern
Improved By : jit_t