숫자 n이 주어지면 그 숫자의 숫자 x를 다른 주어진 숫자 m으로 바꿔야 합니다. 주어진 숫자에 숫자가 있는지 없는지 그 숫자를 찾아야 합니다. 주어진 숫자에 있으면 해당 숫자 x를 다른 숫자 m으로 바꿉니다.
숫자 "123"이 주어지고 m이 5로, 대체될 숫자가 "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\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