একটি সংখ্যা 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