📌  相关文章
📜  通过递增或递减 1、2 或 5 任意次数将 A 转换为 B

📅  最后修改于: 2021-10-25 06:21:21             🧑  作者: Mango

给定两个整数AB ,任务是通过将A增加或减少125任意次数来找到使A等于B所需的最小移动次数。

例子:

方法:可以使用贪心方法解决给定的问题。这个想法是首先找到5的增量或减量,然后是2 ,然后需要1A转换为B 。请按照以下步骤解决问题:

  • A的值更新为AB之间的绝对差值。
  • 现在,打印(A/5) + (A%5)/2 + (A%5)%2 的值作为将A转换为B的最小增量或减量125

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find minimum number of
// moves required to convert A into B
int minimumSteps(int a, int b)
{
    // Stores the minimum number of
    // moves required
    int cnt = 0;
 
    // Stores the absolute
    // differenece
    a = abs(a - b);
 
    // FInd the number of moves
    cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
 
    // Return cnt
    return cnt;
}
 
// Driver Code
int main()
{
    // Input
    int A = 3, B = 9;
    // Function call
    cout << minimumSteps(A, B);
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG
{
   
    // Function to find minimum number of
    // moves required to convert A into B
    static int minimumSteps(int a, int b)
    {
       
        // Stores the minimum number of
        // moves required
        int cnt = 0;
 
        // Stores the absolute
        // differenece
        a = Math.abs(a - b);
 
        // FInd the number of moves
        cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
 
        // Return cnt
        return cnt;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int A = 3, B = 9;
        // Function call
        System.out.println(minimumSteps(A, B));
    }
}
 
 // This code is contributed by Potta Lokesh


Python3
# python program for the above approach
 
# Function to find minimum number of
# moves required to convert A into B
def minimumSteps(a, b):
   
    # Stores the minimum number of
    # moves required
    cnt = 0
 
    # Stores the absolute
    # differenece
    a = abs(a - b)
 
    # FInd the number of moves
    cnt = (a//5) + (a % 5)//2 + (a % 5) % 2
     
    # Return cnt
    return cnt
 
 
# Driver Code
# Input
A = 3
B = 9
 
# Function call
print(minimumSteps(A, B))
 
# This code is contributed by amreshkumar3.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find minimum number of
// moves required to convert A into B
static int minimumSteps(int a, int b)
{
     
    // Stores the minimum number of
    // moves required
    int cnt = 0;
 
    // Stores the absolute
    // differenece
    a = Math.Abs(a - b);
 
    // FInd the number of moves
    cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
 
    // Return cnt
    return cnt;
}
 
// Driver Code
public static void Main()
{
     
    // Input
    int A = 3, B = 9;
     
    // Function call
    Console.Write(minimumSteps(A, B));
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript


输出
2

时间复杂度: O(1)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程