Given two integers A and B. The task is to check whether it is possible to convert A into B by performing below operations any number of times.
- Convert current number x to 2 * x.
- Convert current number x to (10 * x) + 1.
Input: A = 2, B = 82
2 -> 4 -> 41 -> 82
Input: A = 2, B = 5
Approach: Let’s solve this problem in a reverse way – try to get the number A from B.
Note, that if B ends with 1 the last operation was to append the digit 1 to the right of the current number. Because of that let’s delete the last digit of B and move to the new number.
If the last digit is even then the last operation was to multiply the current number by 2. Because of that let’s divide B by 2 and move to the new number.
In the other cases (if B ends with odd digit except 1) the answer is No.
We need to repeat the described algorithm after every time we get a new number. If at some point, we get a number which is equal to A then the answer is Yes, and if the new number is less than A then the answer is No.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Convert given integer X to the form 2^N - 1
- Convert to number with digits as 3 and 8 only
- Program to Convert Octal to Hexadecimal
- Convert the given BCD to its equivalent Binary form
- Menu Driven Program to convert MKS to CGS and CGS to MKS
- Convert a given Decimal number to its BCD representation
- Count the numbers which can convert N to 1 using given operation
- Convert N to M with given operations using dynamic programming
- Program to convert a given number to words
- Program to convert Number in characters
- Convert a String to an Integer using Recursion
- Program to convert Degree to Radian
- Maximum prime moves to convert X to Y
- Program to Convert Radian to Degree
- Convert Binary fraction to Decimal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.