错误代码:
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;int main() {unordered_map<int, string> map = {{0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"},{5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}};int num;cin >> num;int sum = 0;// Handle the case where num is 0if (num == 0) {sum = 0;}else {while (num > 0) {sum += num % 10;num /= 10;}}// Handle the case where sum is 0 (for input num = 0)if (sum == 0) {cout << map[0] << endl;return 0;}vector<int> v;while (sum > 0) {int r = sum % 10;v.push_back(r);sum /= 10;}int length = v.size();for (int i = length - 1; i >= 0; i--) {cout << map[v[i]];if (i != 0) {cout << " ";}}return 0;
}
数字越界
正确代码(用字符串处理):
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;int main() {unordered_map<int, string> map = {{0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"},{5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}};string num;cin >> num;int sum = 0;// Calculate the sum of digitsfor (char c : num) {sum += c - '0';}// If sum is zero, we handle it directlyif (sum == 0) {cout << map[0] << endl;return 0;}vector<int> digits;while (sum > 0) {digits.push_back(sum % 10);sum /= 10;}// Output the digits in Englishfor (int i = digits.size() - 1; i >= 0; i--) {cout << map[digits[i]];if (i != 0) {cout << " ";}}cout << endl;return 0;
}