Q:

C++ program to isolate rightmost one bit of a number

0

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

Constraints: 1<=n<=100

Example:

    Input:
    Enter number: 18

    Output:
    original number before isolating rightmost 1 bit: 18
    new number after isolating rightmost 1 bit: 2

Problem Explanation:

Suppose the given number is 18. Let’s denote rightmost one bit by ROB.

Now the binary representation of 18 is:

    n = 00010010
    mask = -n = 11101110 (toggle all bits and 1 to it)
    Binary representation of number after isolating ROB = n & mask
    n & mask = 00000010
    Hence decimal representation of new number is 2.

This can be explained as follows:

When we create a mask of -n, we observe that only ROB and bits to the right of ROB (which are 0) are identical to the original number.

Therefore, to isolate the ROB we can do bitwise AND of the mask with n as only the ROB is 1 in both the masks.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

  1. Input the number for which ROB is to be isolated.
  2. Create a mask -n (first toggle all bits in n and then add 1 to it).
  3. Perform bitwise AND of the mask created with original number i.e. n & mask where mask is of -n.
  4. Output the result after bitwise AND in decimal form.

C++ Implementation:

#include <iostream>
using namespace std;

int isolate_rightmost_onebit(int n)
{
	//to compute -n, toggle all bits and add 1 to it 
	int mask=-n;
	// new number after isolating rightmost 1 bit 
	return (n&mask);
}

//driver program to check the code
int main() 
{
	int num;

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

	int new_number= isolate_rightmost_onebit(num);

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

	return 0;
}

Output

 
Enter number: 18
original number before isolating rightmost 1 bit: 18
new number after isolating rightmost 1 bit: 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now