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.
- Write an Efficient Method to Check if a Number is Multiple of 3
- Find the Number Occurring Odd Number of Times
- Check for Integer Overflow
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute the integer absolute value (abs) without branching
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Multiply a given Integer with 3.5
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
Improved By : jit_t