For every set bit of a number toggle bits of other in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integer values. Our task is to create a c program to operform the operation, For every set bit of a number toggle bits of other. 

Let’s take an example to understand the problem

Input: 3 7
Output: 4
Binary of 3: 011
Binary of 3: 111

First and second bits of the second number is flipped which makes it 100 i.e 4.

Solution Approach

An approach to solve the problem is by performing the XOR operation of the two numbers. The result will be toggled for the bit where ever the bits of the I’st is 1 using XOR operation.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;

int main(){
   int a = 3, b = 7;
   cout<<"The numbers are "<<a<<" & "<<b<<endl;
   cout<<"The result of flipping bits is "<<(a ^ b);
   return 0;
}

Output

The numbers are 3 & 7
The result of flipping bits is 4
raja
Updated on 01-Feb-2022 08:50:43

Advertisements