用另一個數字替換一個數字的 C 程式
給定一個數字 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.
以下使用的方法如下 −
- 我們將從單位位開始查詢數字
- 當我們找到要替換的數字時,然後將結果新增到 (replace * 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
", 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP