用另一个数字替换一个数字的 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