Maximum steps to transform 0 to X with bitwise AND
For an integer N, there are elements ranging from 0 to N-1. Certain elements can be transformed into other elements. Each transformation requires a certain effort which is equal to 1 unit, for each transformation. An element A can be transformed to element B, if and only if A != B and A & B = A (where & is the bitwise AND operator). We need to find the maximum effort possible to obtain the element with value X, from the element with value 0, by a series of transformations.
Input : X = 2
Output : 1
The only way of obtaining 2 is to directly transform 0 to 2 (bitwise AND of 0 and 2 is 0) and hence requires one step.
Input : X = 3
Output : 2
3 can be obtained in two steps. First, transform 0 to 1 (bitwise AND of 0 and 1 is 0). Then, transform 1 to 3 (bitwise AND of 1 and 3 is 1).
The simple solution is to count the number of set bits in X.
First, consider a single step transformation from A to B. All the set bits (bits which are equal to 1) of A should be set in B, otherwise bitwise AND of A and B will not be equal to A. If there is any bit that is set in A but not in B, then the transformation is not possible. The unset bits of A can either be set or unset in B, it does not matter. We can then change A to B by setting all the unset bits in A in one single step. Consequently, if we had to transform 0 to X in the least steps, the answer would have been one because bitwise AND of 0 with any number is 0.
But we have to compute the maximum steps. So in each step, we set each bit starting from the right and a set bit can not be cleared once it set.
Suppose we want to obtain 13 (1101 in binary) from 0. We start by setting the 1st bit from the right by transforming 0 to 1 (0001 in binary). We next set the 3rd bit from the right to form 5 (0101 in binary). The last step would be to set the 4th bit and obtain 13 (1101).
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.