Given a non-negative number n. The problem is to set the rightmost unset bit in the binary representation of n
Input : 21 Output : 23 (21)10 = (10101)2 Rightmost unset bit is at position 2(from right) as highlighted in the binary representation of 21. (23)10 = (10111)2 The bit at position 2 has been set. Input : 2 Output : 3
One method is discussed in this article
This post discusses another method.
Let the input number be n. n+1 would have all the bits flipped after the rightmost unset bit (including the unset bit). So, doing n|(n+1) would give us the required result.
The number after setting the rightmost unset bit 7
- Position of rightmost set bit
- Turn off the rightmost set bit
- Position of rightmost different bit
- Set the rightmost unset bit
- Find the largest number with n set and m unset bits
- Unset bits in the given range
- Get the position of rightmost unset bit
- Find the smallest number with n set and m unset bits
- Position of rightmost common bit in two numbers
- Check whether all the bits are unset in the given range or not
- Count unset bits of a number
- Unset the last m bits
- Set the Left most unset bit
- Count unset bits in a range
- Position of rightmost bit with first carry in sum of two binary
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.