使用C ++中给定操作的最小数目将数字m转换为n
在本教程中,我们将讨论一个程序,该程序使用最少的给定操作数将m转换为n。
为此,我们将提供两个整数m和n。我们的任务是使用给定的操作最少次数将整数m转换为n。
允许的操作-
给定数字乘以2
从给定的数字中减去一个
示例
#include <bits/stdc++.h>
using namespace std;
//finding minimum number of operations required
int convert(int m, int n){
if (m == n)
return 0;
if (m > n)
return m - n;
//can't convert in this situation
if (m <= 0 && n > 0)
return -1;
//when n is greater and n is odd
if (n % 2 == 1)
//performing '-1' on m
return 1 + convert(m, n + 1);
//when n is even
else
//performing '*2' on m
return 1 + convert(m, n / 2);
}
int main(){
int m = 5, n = 11;
cout << "Minimum number of operations : " << convert(m, n);
return 0;
}输出结果
Minimum number of operations : 5
热门推荐
10 晚来的生日祝福语简短
11 私房进火祝福语简短
12 婆婆去世的祝福语简短
13 古风祝福语 唯美简短结婚
14 幼师离别祝福语老师简短
15 伴娘祝福语简短朋友的话
16 生日祝福语 简短独特潮
17 过年红包祝福语简短霸气
18 生日高考祝福语妹妹简短