Computer >> Máy Tính >  >> Lập trình >> lập trình C

C Chương trình thay thế một chữ số bằng chữ số khác

Cho một số n, chúng ta phải thay một chữ số x từ số đó bằng một số cho trước khác m. chúng ta phải tìm số cho dù số đó có trong một số đã cho hay không, nếu nó có trong một số đã cho thì hãy thay số cụ thể đó x bằng một số khác m.

Giống như chúng ta được cho một số “123” và m là 5 và số được thay thế, tức là x thành “2”, vì vậy kết quả sẽ là “153”.

Ví dụ

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.

Phương pháp được sử dụng bên dưới như sau -

  • Chúng tôi sẽ tìm kiếm số bằng cách bắt đầu từ vị trí đơn vị
  • Khi chúng tôi tìm thấy chữ số mà chúng tôi muốn thay thế, hãy thêm kết quả vào (thay thế * d) trong đó d phải bằng 1.
  • Nếu chúng tôi không tìm thấy số, chỉ cần giữ nguyên số đó.

Thuật toán

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

Ví dụ

#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;
}

Nếu chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -

783