ให้ตัวเลข n เราต้องแทนที่หลัก x จากตัวเลขนั้นด้วยตัวเลขอื่นที่กำหนด m เราต้องมองหาตัวเลขว่าตัวเลขนั้นอยู่ในตัวเลขที่ให้มาหรือไม่ ถ้ามี ให้แทนที่ตัวเลขนั้น x ด้วยตัวเลขอื่น m
เช่นเดียวกับที่เราได้รับตัวเลข “123” และ m เป็น 5 และตัวเลขที่จะแทนที่เช่น x เป็น “2” ดังนั้นผลลัพธ์ควรเป็น “153”
ตัวอย่าง
Input: n = 983, digit = 9, replace = 6 Output: 683 Explanation: digit 9 is the first digit in 983 and we have to replace the digit 9 with 6 so the result will be 683. Input: n = 123, digit = 5, replace = 4 Output: 123 Explanation: There is not digit 5 in the given number n so the result will be same as the number n.
แนวทางที่ใช้ด้านล่างมีดังนี้ −
- เราจะค้นหาตัวเลขโดยเริ่มจากตำแหน่งหน่วย
- เมื่อเราพบตัวเลขที่เราต้องการแทนที่แล้ว ให้เพิ่มผลลัพธ์ลงใน (แทนที่ * d) โดยที่ d ควรเท่ากับ 1
- หากเราไม่พบตัวเลข ก็แค่เก็บตัวเลขไว้ตามเดิม
อัลกอริทึม
In function int digitreplace(int n, int digit, int replace) Step 1-> Declare and initialize res=0 and d=1, rem Step 2-> Loop While(n) Set rem as n%10 If rem == digit then, Set res as res + replace * d Else Set res as res + rem * d d *= 10; n /= 10; End Loop Step 3-> Print res End function In function int main(int argc, char const *argv[]) Step 1-> Declare and initialize n = 983, digit = 9, replace = 7 Step 2-> Call Function digitreplace(n, digit, replace); Stop
ตัวอย่าง
#include <stdio.h>
int digitreplace(int n, int digit, int replace) {
int res=0, d=1;
int rem;
while(n) {
//finding the remainder from the back
rem = n%10;
//Checking whether the remainder equal to the
//digit we want to replace. If yes then replace.
if(rem == digit)
res = res + replace * d;
//Else dont replace just store the same in res.
else
res = res + rem * d;
d *= 10;
n /= 10;
}
printf("%d\n", res);
return 0;
}
//main function
int main(int argc, char const *argv[]) {
int n = 983;
int digit = 9;
int replace = 7;
digitreplace(n, digit, replace);
return 0;
} หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
783