Number formed by the rightmost set bit in N
Given an integer N, the task is to find an integer M formed by taking the rightmost set bit in N i.e. the only set bit in M will be the rightmost set bit in N nd the rest of the bits will be unset.
Input: N = 7
7 = 111, the number formed by the last set bit is 001 i.e. 1.
Input: N = 10
10 = 1010 -> 0010 = 2
Input: N = 16
- Store x = n & (n – 1) which will unset the first set bit from the right in n.
- Now, update n = n ^ x to set the changed bit and unset all the others which is the required integer.
Below is the implementation of the above approach:
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.