酷代码 AI
菜单
服务商

C++ 实现:从含数字字符串中拼出最大正整数

```cpp #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string s; // 读取输入的字符串 cin >> s; string numbers; // 遍历字符串,提取其中的数字 for (char c : s) { if (isdigit(c) && c != '0') { numbers += c; } } // 对提取的数字进行降序排序 sort(numbers.begin(), numbers.end(), greater<char>()); // 统计字符串中 0 的数量 int zeroCount = 0; for (char c : s) { if (c == '0') { zeroCount++; } } // 如果有非零数字,在排序后的数字后面添加所有的 0 if (!numbers.empty()) { numbers.append(zeroCount, '0'); } else { // 如果没有非零数字,只能拼成 0 numbers = "0"; } // 输出能拼成的最大正整数 cout << numbers << endl; return 0; } ``` 代码解释 1. 输入读取:使用 `cin` 读取输入的字符串 `s`。 2. 提取数字:遍历字符串 `s`,将其中的非零数字添加到 `numbers` 字符串中。 3. 排序:对 `numbers` 字符串进行降序排序,以确保数字按从大到小的顺序排列。 4. 统计 0 的数量:再次遍历字符串 `s`,统计其中 0 的数量。 5. 拼接结果:如果 `numbers` 不为空,在其后面添加所有的 0;如果为空,将结果设为 "0"。 6. 输出结果:输出最终的字符串 `numbers`,即能拼成的最大正整数。 ######[AI问答 | 441点数解答 | 2025-11-08 20:56:33]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]