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
mask1 = 00001100 (add 1 to n)
mask2 = 11110100 (bitwise complement of n)
Binary representation of number after isolating RZB = mask1 & mask2
mask1 & mask2 = 00000100
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:
C++ Implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer