使用 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
广告
数据结构
网络技术
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP