Q:

# C++ program to isolate rightmost zero bit of a number

To write a C++ program to isolate rightmost zero bit of a number.

Constraints: 1<=n<=100

Example:

```    Input:
Enter number: 11

Output:
original number before isolating rightmost 0 bit: 11
new number after isolating rightmost 0 bit: 4
```

Problem Explanation:

Suppose the given number is 11. Let’s denote rightmost zero bit by RZB.

Now the binary representation of 11 is:

```    n = 00001011
mask2 = 11110100 (bitwise complement of n)
Hence decimal representation of new number is 4.
```

This can be explained as follows:

When we add 1 to n the RZB is changed to 1 and all the bits to the right of RZB becomes zero and all the bits to the left are unchanged.

When we do bitwise complement of n, the RZB is changed to 1. The bits to the right of RZB become 0 and bits to the left are toggled.

Therefore to isolate the RZB we can do bitwise AND of the two masks as only the RZBis 1 in both the masks.

Algorithm:

1. Input the number for which RZB is to be isolated.
3. Create a mask2 by performing bitwise complement of original number (toggle all bits).
5. Output the result after bitwise AND in decimal form.

C++ Implementation:

``````#include <iostream>
using namespace std;

int isolate_rightmost_zerobit(int n)
{
int mask2=~(n);         // bitwise complement of original number
}

//driver program to check the code

int main()
{
int num;

cout<<"Enter number: ";
cin>>num;
cout<<"original number before isolating rightmost 0 bit: "<<num<<endl;

int new_number= isolate_rightmost_zerobit(num);

cout<<"new number after isolating rightmost 0 bit: "<<new_number<<endl;

return 0;
}``````

Output

```Enter number: 11
original number before isolating rightmost 0 bit: 11
new number after isolating rightmost 0 bit: 4 ```