给定两个整数A和B ,通过多次执行以下操作之一,将A转换为B :
- A = A + K
- A = A – K ,其中K属于[1,10]
任务是找到使用上述操作将A转换为B所需的最少操作数。
例子:
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).
方法:这个想法是通过将A和B的绝对差除以[1…10]范围内的所有数字,并将其加到结果变量中来简单地计算所需的移动次数。请按照以下步骤解决问题:
- 初始化变量required_moves以存储所需的最少移动次数。
- 求出A和B的绝对差。
- 迭代范围[ 1,10 ]并执行以下操作:
- 将数字除以i,然后将其添加到结果变量中。
- 用i计算绝对差的模。
- 最后,打印required_moves的值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find minimum number
// of moves to obtained B from A
void convertBfromA(int a, int b)
{
// Stores the minimum
// number of moves
int moves = 0;
// Absolute difference
int x = abs(a - b);
// K is in range [0, 10]
for (int i = 10; i > 0; i--) {
moves += x / i;
x = x % i;
}
// Print the required moves
cout << moves << " ";
}
// Driver Code
int main()
{
int A = 188, B = 4;
convertBfromA(A, B);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to find minimum number
// of moves to obtained B from A
static void convertBfromA(int a, int b)
{
// Stores the minimum
// number of moves
int moves = 0;
// Absolute difference
int x = Math.abs(a - b);
// K is in range [0, 10]
for(int i = 10; i > 0; i--)
{
moves += x / i;
x = x % i;
}
// Print the required moves
System.out.print(moves + " ");
}
// Driver Code
public static void main (String[] args)
{
int A = 188, B = 4;
convertBfromA(A, B);
}
}
// This code is contributed by code_hunt
Python3
# Python3 program for the above approach
# Function to find minimum number
# of moves to obtained B from A
def convertBfromA(a, b):
# Stores the minimum
# number of moves
moves = 0
# Absolute difference
x = abs(a - b)
# K is in range [0, 10]
for i in range(10, 0, -1):
moves += x // i
x = x % i
# Print the required moves
print(moves, end = " ")
# Driver Code
A = 188
B = 4
convertBfromA(A, B)
# This code is contributed by code_hunt
C#
// C# program for the above approach
using System;
class GFG{
// Function to find minimum number
// of moves to obtained B from A
static void convertBfromA(int a, int b)
{
// Stores the minimum
// number of moves
int moves = 0;
// Absolute difference
int x = Math.Abs(a - b);
// K is in range [0, 10]
for(int i = 10; i > 0; i--)
{
moves += x / i;
x = x % i;
}
// Print the required moves
Console.Write(moves + " ");
}
// Driver Code
public static void Main ()
{
int A = 188, B = 4;
convertBfromA(A, B);
}
}
// This code is contributed by code_hunt
输出:
19
时间复杂度: O(K),其中K在[0,10]范围内
辅助空间: O(1)