ภารกิจคือการเพิ่มจำนวนที่กำหนดให้สูงสุดด้วยจำนวนหลัก 'N' โดยการแทนที่ตัวเลขโดยใช้อาร์เรย์อื่นที่มี 10 หลักเป็นทางเลือกสำหรับตัวเลขหลักเดียวทั้งหมด 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() ให้สร้างตัวแปร 'N' ของประเภท int เพื่อเก็บขนาดของตัวเลข
-
วนจาก i=0 จนถึง i
-
จากนั้นแทนที่หมายเลขด้วยหมายเลขอื่น
-
ทำเช่นนี้สำหรับหมายเลขที่จะมาถึงจนกว่าจะไม่พบตัวเลขที่มีทางเลือกน้อยกว่า
ตัวอย่าง
#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