当前位置: 首页> 科技> 数码 > PTA甲级1005:Spell It Right

PTA甲级1005:Spell It Right

时间:2025/7/12 14:50:11来源:https://blog.csdn.net/m0_75015083/article/details/140253602 浏览次数:4次

错误代码:

#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;
}

关键字:PTA甲级1005:Spell It Right

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: