在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