एक संख्या 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