Given a initial number x and two operations which are given below:
- Multiply number by 2.
- Subtract 1 from the number.
The task is to find out minimum number of operation required to convert number x into y using only above two operations. We can apply these operations any number of times.
1 <= x, y <= 10000
Input : x = 4, y = 7 Output : 2 We can transform x into y using following two operations. 1. 4*2 = 8 2. 8-1 = 7 Input : x = 2, y = 5 Output : 4 We can transform x into y using following four operations. 1. 2*2 = 4 2. 4-1 = 3 3. 3*2 = 6 4. 6-1 = 5 Answer = 4 Note that other sequences of two operations would take more operations.
The idea is to use BFS for this. We run a BFS and create nodes by multiplying with 2 and subtracting by 1, thus we can obtain all possible numbers reachable from starting number.
Important Points :
1) When we subtract 1 from a number and if it becomes < 0 i.e. Negative then there is no reason to create next node from it (As per input constraints, numbers x and y are positive).
2) Also, if we have already created a number then there is no reason to create it again. i.e. we maintain a visited array.
This article is contributed by Vipin Khushu. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Minimum number of given operations required to convert a permutation into an identity permutation
- Minimum number of swaps required to sort an array
- Minimum number of given operations required to make two strings equal
- Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
- Minimum time required to rot all oranges
- Minimum edges required to add to make Euler Circuit
- Minimum number of edges between two vertices of a Graph
- Minimum number of edges between two vertices of a graph using DFS
- Minimum number of prefix reversals to sort permutation of first N numbers
- Find the minimum number of moves needed to move from one cell of matrix to another
- Find the number of islands | Set 1 (Using DFS)
- Number of Transpositions in a Permutation
- Number of Hamiltonian cycle
- Number of Walks from source to destination
- Print all the levels with odd and even number of nodes in it | Set-2