Count minimum moves required to convert A to B
Last Updated :
28 Sep, 2021
Given two integers A and B, convert A to B by performing one of the following operations any number of times:
- A = A + K
- A = A – K, where K belongs to [1, 10]
The task is to find the minimum number of operations required to convert A to B using the above operations.
Examples:
Input: A = 13, B = 42
Output: 3
Explanation:
The following sequence of moves can be performed: 13 ? 23 ? 32 ? 42(add 10, add 9, add 10).
Input: A = 18, B = 4
Output: 2
Explanation:
The following sequence of moves can be performed: 18 ? 10 ? 4 (subtract 8, subtract 6).
Approach: The idea is to simply calculate the required number of moves by dividing the absolute difference of A and B by all the numbers in the range [1…10] and adding it to the resultant variable. Follow the steps below to solve the problem:
- Initialize a variable required_moves to store the minimum count of moves required.
- Find the absolute difference of A and B.
- Iterate over the range [1, 10] and perform the following operations:
- Divide the number by i and add it to the resultant variable.
- Calculate modulo of absolute difference by i.
- Finally, print the value of required_moves.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void convertBfromA( int a, int b)
{
int moves = 0;
int x = abs (a - b);
for ( int i = 10; i > 0; i--) {
moves += x / i;
x = x % i;
}
cout << moves << " " ;
}
int main()
{
int A = 188, B = 4;
convertBfromA(A, B);
return 0;
}
|
Java
import java.io.*;
class GFG{
static void convertBfromA( int a, int b)
{
int moves = 0 ;
int x = Math.abs(a - b);
for ( int i = 10 ; i > 0 ; i--)
{
moves += x / i;
x = x % i;
}
System.out.print(moves + " " );
}
public static void main (String[] args)
{
int A = 188 , B = 4 ;
convertBfromA(A, B);
}
}
|
Python3
def convertBfromA(a, b):
moves = 0
x = abs (a - b)
for i in range ( 10 , 0 , - 1 ):
moves + = x / / i
x = x % i
print (moves, end = " " )
A = 188
B = 4
convertBfromA(A, B)
|
C#
using System;
class GFG{
static void convertBfromA( int a, int b)
{
int moves = 0;
int x = Math.Abs(a - b);
for ( int i = 10; i > 0; i--)
{
moves += x / i;
x = x % i;
}
Console.Write(moves + " " );
}
public static void Main ()
{
int A = 188, B = 4;
convertBfromA(A, B);
}
}
|
Javascript
<script>
function convertBfromA(a, b)
{
let moves = 0;
let x = Math.abs(a - b);
for (let i = 10; i > 0; i--)
{
moves += Math.floor(x / i);
x = x % i;
}
document.write(moves + " " );
}
let A = 188, B = 4;
convertBfromA(A, B);
</script>
|
Time Complexity: O(K), where K is in the range [0, 10]
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...