In this shot, we’re going to look at how to set the rightmost unset bit of an input number and return the number obtained.
For example, given an input of , we’ll obtain an output of . This is because in binary form is . When we set its rightmost unset bit, we get , that is, .
As another example, we get an output of when we provide an input of . This is because in binary form is . There are no unset bits in the binary representation of . Hence, the value returned is also .
Note: Refer to How to check if all bits are set in a number? to check if all bits in a number are set.
Now, let’s test the following expression:
n | (n + 1)
The above expression sets the rightmost unset bit. But it may set a leading zero bit if the given number doesn’t contain any unset bits. For example, consider setting n=7
in the above function:
Expression | Result |
---|---|
n=7 | 0111 |
n+1=8 | 1000 |
n | (n + 1) |
Though there are no unset bits in , the expression n | (n + 1)
still sets the rightmost unset bit.
Hence, it’s essential first to check if there are no unset bits in the given number.
class Main{ static int setRightmostUnsetBit(int n){ if((n & (n+1)) == 0) return n; return (n | (n+1)); } public static void main(String[] args) { int n = 8; System.out.println("Setting the rightmost unset bit of " + n + " we get " + setRightmostUnsetBit(n)); } }
setRightmostUnsetBit()
such that it implements the solution discussed above to set the rightmost unset bit of n
.n
.setRightmostUnsetBit()
with n
as a parameter.RELATED TAGS
CONTRIBUTOR
View all Courses