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 email@example.com. 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 swaps required to sort an array
- Minimum number of given operations required to make two strings equal
- 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 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
- Number of Transpositions in a Permutation
- Find the number of islands | Set 1 (Using DFS)
- Number of days until all chocolates become unhealthy
- Number of Unicolored Paths between two nodes
- Number of sink nodes in a graph
- Count number of trees in a forest
- Number of Walks from source to destination
- Count the number of non-reachable nodes
Improved By : rahulpopat