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.
- Position of rightmost set bit
- Turn off the rightmost set bit
- Position of rightmost different 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
- Check whether the bit at given position is set or unset