Given a non-negative number n. Find the position of rightmost unset bit in the binary representation of n, considering the last bit at position 1, 2nd last bit at position 2 and so on. If no 0’s are there in the binary representation of n. then print “-1”.
Input : n = 9 Output : 2 (9)10 = (1001)2 The position of rightmost unset bit in the binary representation of 9 is 2. Input : n = 32 Output : 1
Approach: Following are the steps:
- If n = 0, return 1.
- If all bits of n are set, return -1. 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. This will be the position of rightmost unset bit of 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 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.
- Position of rightmost set bit
- Turn off the rightmost set bit
- Find position of the only 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
- Find the smallest number with n set and m unset bits
- Extract 'k' bits from a given position in a number.
- 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
- Modify a bit at a given position
- Unset the last m bits
- Set the Left most unset bit
Improved By : vt_m