#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; string s; int y, n, pre[10000]; int main() { while (cin >> s >> y) { int sum = 0; for (int i = 0; i < s.length(); i++) { sum += s[i] - '0'; } if (sum == y) { cout << s << '\n'; continue; } if (y == 0) { cout << "-1\n"; continue; } if (y > s.length() * 9) { if (y % 9) cout << y % 9; for (int i = 0; i < y / 9; i++) cout << 9; cout << "\n"; continue; } s = '0' + s; n = s.length(); for (int i = 1; i <= n; i++) { pre[i] = pre[i - 1] + s[i - 1] - '0'; } for (int i = n; i >= 1; i--) { if (s[i - 1] == '9') continue; if (pre[i] < y && y - pre[i - 1] <= 9 * (n - i + 1)) { int less = y - pre[i] - 1; for (int j = n - 1; j >= i; j--) { if (less < 9) { s[j] = '0' + less; less = 0; continue; } if (less == 0) { s[j] = '0'; continue; } s[j] = '9'; less -= 9; } s[i - 1] += less + 1; if (s[0] == '0') s.erase(s.begin()); cout << s << '\n'; break; } } } }转化为c语言
时间: 2023-12-02 17:04:10 浏览: 85
#include <iostream>
以下是将该段代码转化为 C 语言的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[10005];
int y, n, pre[10005];
int main() {
while (scanf("%s %d", s, &y) == 2) {
int sum = 0;
for (int i = 0; i < strlen(s); i++) {
sum += s[i] - '0';
}
if (sum == y) {
printf("%s\n", s);
continue;
}
if (y == 0) {
printf("-1\n");
continue;
}
if (y > strlen(s) * 9) {
if (y % 9)
printf("%d", y % 9);
for (int i = 0; i < y / 9; i++)
printf("9");
printf("\n");
continue;
}
n = strlen(s);
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + s[i - 1] - '0';
}
for (int i = n; i >= 1; i--) {
if (s[i - 1] == '9') {
continue;
}
if (pre[i] < y && y - pre[i - 1] <= 9 * (n - i + 1)) {
int less = y - pre[i] - 1;
for (int j = n - 1; j >= i; j--) {
if (less < 9) {
s[j] = '0' + less;
less = 0;
continue;
}
if (less == 0) {
s[j] = '0';
continue;
}
s[j] = '9';
less -= 9;
}
s[i - 1] += less + 1;
if (s[0] == '0') {
memmove(s, s + 1, strlen(s));
}
printf("%s\n", s);
break;
}
}
}
return 0;
}
```
阅读全文