在C++中,通过用C++中给定的备选数字替换一段数字,来最大化给定的数字
给定的任务是通过使用另一个包含0到9所有个位数的备选数字的数组来替换其数字,从而最大化一个具有'N'位数字的给定数字。
给定的条件是只能替换连续的一段数字,并且只能替换一次。
输入
N=1234, arr[]={3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4}输出
1257
说明
数字3可以用其备选数字5替换,即arr[3]
数字4可以用其备选数字7替换,即arr[4]
输入
N=5183, arr[]={3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4}输出
7183
下面程序中使用的方案如下
在Max()函数中创建一个int类型的变量'N'来存储数字的大小。
循环从i=0到i<N,并检查其备选数字大于自身的数字。
然后用其备选数字替换该数字。
对接下来的数字重复此操作,直到找到一个备选数字小于自身的数字。
示例
#include <bits/stdc++.h>
using namespace std;
string Max(string str, int arr[]){
int N = str.size();
//Iterating till the end of string
for (int i = 0; i < N; i++) {
//Checking if it is greater or not
if (str[i] - '0' < arr[str[i] - '0']) {
int j = i;
//Replacing with the alternate till smaller
while (j < N && (str[j] - '0' <= arr[str[j] - '0'])) {
str[j] = '0' + arr[str[j] - '0'];
j++;
}
return str;
}
}
// Returning original str if there is no change
return str;
}
//Main function
int main(){
string str = "2075";
int arr[] = {3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4 };
cout <<” Maximize the given number by replacing a segment of digits with the alternate digits given is: ” <<Max(str, arr);
return 0;
}输出
如果我们运行上面的代码,我们将得到以下输出:
Maximize the given number by replacing a segment of digits with the alternate digits given is: 2375
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP