Alternate bits of two numbers to create a new number in C++


In this problem, we need to generate a number by using alternate bits of two numbers. So, in this problem we will use the first bit from the second number, then second bit from first, the third bit again from the second number and forth from first and so on.

From first, the third bit again from the second number and forth from first and so on.

Lets take an example to understand the topic better,

Input : n = 6 m = 10
Output : 2
Explanation :
Bits representation of 6 = 0110
Bit representation of 10 = 1010
0 1 1 0
^ ^
1 0 1 0
^ ^
= 0 0 1 0 = 2

Now, through this example, the point is clear that what we need to do to solve the code. Basically the solution is to take alternate bits from the numbers starting from the LSB of the second number.

To solve this problem one feasible approach is to find set even bits of the first number n and then find set odd bits of the second number m and return the bitwise OR of the two.

Algorithm

Step 1 : For n find the value of set even bits.
Step 2 : For m find the value of set odd bits.
Step 3 : Calculate the result = set even bits of n | set odd bits of m.
Step 4: Print the value of result.

Example

 Live Demo

#include <iostream>
using namespace std;
int setevenbits(int n) ;
int setoddbits(int m) ;
int main(){
   int n = 12;
   int m = 17;
   int setn = setevenbits(n);
   int setm = setoddbits(m);
   int result = ( setn | setm );
   cout<<result;
   return 0;
}
int setevenbits(int n){
   int temp = n;
   int count = 0;
   int res = 0;
   for (temp = n; temp > 0; temp >>= 1) {
      if (count % 2 == 1)
         res |= (1 << count);
      count++;
   }
   return (n & res);
}
int setoddbits(int m){
   int count = 0;
   int res = 0;
   for (int temp = m; temp > 0; temp >>= 1) {
      if (count % 2 == 0)
         res |= (1 << count);
      count++;
   }
   return (m & res);
}

Output

25

Updated on: 16-Oct-2019

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements