给定两个整数N和M 。任务是通过执行给定的操作找到从 N 到达 M 的最少步数。
- 将数字 x 乘以 2。因此,x 变为 2*x。
- 从数字 x 中减去一。因此,x 变为 x-1。
例子:
Input : N = 4, M = 6
Output : 2
Explanation : Perform operation number 2 on N.
So, N becomes 3 and then perform operation number 1.
Then, N becomes 6. So, the minimum number of steps is 2.
Input : N = 10, M = 1
Output : 9
Explanation : Perform operation number two
9 times on N. Then N becomes 1.
方法:
这个想法是将问题反转如下:我们应该使用以下操作从 M 开始得到数字 N:
- 如果是偶数,则将数字除以 2。
- 在数字上加 1。
现在,最少的操作次数是:
- 如果 N > M,则返回它们之间的差值,即步数将在 M 上加 1,直到它等于 N。
- 否则如果 N < M。
- 继续将 M 除以 2,直到它小于 N。如果 M 是奇数,则先加 1,然后除以 2。一旦 M 小于 N,将它们之间的差与上述操作的计数一起添加到计数中.
下面是上述方法的实现:
C++
// CPP program to find minimum number
// of steps to reach M from N
#include
using namespace std;
// Function to find a minimum number
// of steps to reach M from N
int Minsteps(int n, int m)
{
int ans = 0;
// Continue till m is greater than n
while(m > n)
{
// If m is odd
if(m&1)
{
// add one
m++;
ans++;
}
// divide m by 2
m /= 2;
ans++;
}
// Return the required answer
return ans + n - m;
}
// Driver code
int main()
{
int n = 4, m = 6;
cout << Minsteps(n, m);
return 0;
}
Java
// Java program to find minimum number
// of steps to reach M from N
class CFG
{
// Function to find a minimum number
// of steps to reach M from N
static int Minsteps(int n, int m)
{
int ans = 0;
// Continue till m is greater than n
while(m > n)
{
// If m is odd
if(m % 2 != 0)
{
// add one
m++;
ans++;
}
// divide m by 2
m /= 2;
ans++;
}
// Return the required answer
return ans + n - m;
}
// Driver code
public static void main(String[] args)
{
int n = 4, m = 6;
System.out.println(Minsteps(n, m));
}
}
// This code is contributed by Code_Mech
Python3
# Python3 program to find minimum number
# of steps to reach M from N
# Function to find a minimum number
# of steps to reach M from N
def Minsteps(n, m):
ans = 0
# Continue till m is greater than n
while(m > n):
# If m is odd
if(m & 1):
# add one
m += 1
ans += 1
# divide m by 2
m //= 2
ans += 1
# Return the required answer
return ans + n - m
# Driver code
n = 4
m = 6
print(Minsteps(n, m))
# This code is contributed by mohit kumar
C#
// C# program to find minimum number
// of steps to reach M from N
using System;
class GFG
{
// Function to find a minimum number
// of steps to reach M from N
static int Minsteps(int n, int m)
{
int ans = 0;
// Continue till m is greater than n
while(m > n)
{
// If m is odd
if(m % 2 != 0)
{
// add one
m++;
ans++;
}
// divide m by 2
m /= 2;
ans++;
}
// Return the required answer
return ans + n - m;
}
// Driver code
public static void Main()
{
int n = 4, m = 6;
Console.WriteLine(Minsteps(n, m));
}
}
// This code is contributed
// by Akanksha Rai
PHP
$n)
{
// If m is odd
if($m % 2 != 0)
{
// add one
$m++;
$ans++;
}
// divide m by 2
$m /= 2;
$ans++;
}
// Return the required answer
return $ans + $n - $m;
}
// Driver code
$n = 4; $m = 6;
echo(Minsteps($n, $m));
// This code is contributed by Code_Mech
?>
Javascript
输出:
2
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。