#include <iostream> #include <algorithm> #include <vector> #include <string>使用命名空间 std;字符串 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”;继续;} 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') 继续; 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';小于 -= 9;} s[i - 1] += 少 + 1;if (s[0] == '0') s.erase(s.begin());cout << s<< '\n';破;}} } }转为c语言
时间: 2023-12-04 14:05:23 浏览: 69
把这段代码转换为C语言,需要做以下修改:
1. 替换命名空间std为全局作用域。
2. 替换字符串类string为字符数组。
3. 替换输入输出流iostream为stdio.h头文件中的scanf和printf函数。
4. 去掉vector容器。
5. 把continue语句改为goto语句。
6. 把erase函数改为memmove函数。
修改后的代码如下:
```c
#include <stdio.h>
#include <string.h>
char s[10001];
int y, n, pre[10001];
int main() {
while (scanf("%s %d", s, &y) == 2) {
int sum = 0;
n = strlen(s);
for (int i = 0; i < n; i++) {
sum += s[i] - '0';
}
if (sum == y) {
printf("%s\n", s);
continue;
}
if (y == 0) {
printf("-1\n");
continue;
}
if (y > n * 9) {
if (y % 9)
printf("%d", y % 9);
for (int i = 0; i < y / 9; i++)
printf("9");
printf("\n");
goto end;
}
s[n + 1] = '\0';
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')
goto end;
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, n);
printf("%s\n", s);
goto end;
}
}
end:;
}
return 0;
}
```
阅读全文