Convert X into Y by repeatedly multiplying X with 2 or appending 1 at the end
Given two positive integers X and Y, the task is to check if it is possible to convert the number X into Y, either by multiplying X by 2 or appending 1 at the end of X. If it is possible to convert X into Y, then print “Yes”. Otherwise, print “No”.
Input: X = 100, Y = 40021
Below are the operations performed to convert X into Y:
Operation 1: Multiply X(= 100) by 2, modifies the value X to 200.
Operation 2: Append 1 at the end of X(= 200), modifies the value X to 2001.
Operation 3: Multiply X(= 2001) by 2, modifies the value X to 4002.
Operation 4: Append 1 at the end of X(= 4002), modifies the value X to 40021.
Therefore, from the above operations, it can be seen that the value X can be converted into Y. Hence, print Yes.
Input: X = 17 and Y = 35
Approach: The given problem can be solved by performing the operations in the reverse way i.e., try to convert the value Y into X. Follow the steps below to solve the problem:
- Iterate until the value of Y is greater than X and perform the following steps:
- After completing the above steps, if the value of Y is the same as the value of X, then print Yes. Otherwise, print No.
Below is the implementation of the above approach:
Time Complexity: log(Y)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.