Maximum steps to transform 0 to X with bitwise AND in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer X. Our task is to find the total number of steps that are taken to transform from 0 to X.

Valid transformation − One step is counted when one transformation takes place from A to B. The condition for the transform to take place is A != B and A & B = A (& is bitwise AND). So, 1 step is transforming from A to B and we have to create a program that will count the maximum number of steps to transform 0 to X.

Let’s take an example to understand the problem,

Input − X = 7

Output − 3

Explanation

We have to transform from 0 to 7.

Steps taken will be
Step1: 0(00) to 1(01) , 0!= 1 and 0&1 = 0, transform 00=>01
Step2: 1(001) to 3(011) , 1!= 3 and 1&3 = 1, transform 001=>011
Step3: 3(0011) to 7(0111) , 3!= 7 and 3&7 = 3, tranform 0011=>0111.

To solve this problem, we will be counting the number of set bits in X which will give the maximum transformation from 0 to X.

As we need the maximum transformation, we have to go step by step for each set bit(the bit with value 1). Bit after bit will transformation will give the maximum steps to transform from 0 to X.

In the transformation from A to B, all the set bits of A should be set in B, but the reverse is not necessary. So, the minimum transformation could be 1 as there are no set bits in 0 which makes the smallest conversion direct.

As we can see in the example we have taken, the binary conversion on numbers and their bitwise ANDs.

Example

Program to show the implementation of our solution −

//Program to find Maximum steps to transform 0 to X with bitwise AND in C++

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxtransformation(int x){
   int steps = 0;
   // counting number of bits
   while (x) {
      steps += x & 1;
      x >>= 1;
   }
   return steps;
}
int main(){
   int x = 7;
   cout<<"The maximum number of steps to transform 0 to "<<x<<" with bitwise AND are "<<maxtransformation(x);
   return 0;
}

Output

The maximum number of steps to transform 0 to 7 with bitwise AND are 3
raja
Published on 30-Jan-2020 11:48:39
Advertisements