Given a non-negative number n. The problem is to set the rightmost unset bit in the binary representation of n. If there are no unset bits, then just leave the number as it is.
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 : 15 Output : 15
Approach: Following are the steps:
- If n = 0, return 1.
- If all bits of n are set, return n. Refer this post.
- Else perform bitwise not on the given number(operation equivalent to 1’s complement). Let it be num = ~n.
- Get the position of rightmost set bit of num. Let the position be pos.
- Return (1 << (pos – 1)) | n.
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.
- Set the rightmost unset bit
- Get the position of rightmost unset bit
- Set the rightmost off bit
- Position of rightmost different bit
- Position of rightmost set bit
- Turn off the rightmost set bit
- Number formed by the rightmost set bit in N
- Position of rightmost common bit in two numbers
- Position of rightmost bit with first carry in sum of two binary
- Set the Left most unset bit
- Unset the last m bits
- Check whether the bit at given position is set or unset
- Unset bits in the given range
- Count unset bits in a range
- Check whether all the bits are unset in the given range or not