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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes