通过用C ++中提供的备用数字替换数字段来最大化给定数字
给定任务是通过使用另一个包含10位数字的数组替换其数字来最大化给定数字以'N'个数字,以替代所有0到9的单个数字。
给定条件是只能替换连续的数字段,并且只能替换一次。
输入值
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