使用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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便