PTA (Advanced Level) 1005 Spell It Right
Spell It Right
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤).
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
Sample Input:
12345
Sample Output:
one five
题目解析
本题给出一个小于10的100次方的数字,要求计算其每一位的数字的和,并由最大为开始以英文输出和的每一位。
将给出的数字记录在字符串num中计算字符串每一位减去字符’0’后的和即可得到给出数字每一位的和,以字符串数组str[ ]记录其下标数字对应的英文单词。
最后将得到的和每一位对应的单词记录并输出即可。
1 #include <bits/stdc++.h> 2 using namespace std; 3 const string str[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; 4 int getSum(string num){ //计算给出数字每一位的和 5 int ans = 0; 6 for(auto i : num) 7 ans += i - '0'; 8 return ans; 9 } 10 int main() 11 { 12 string num; 13 cin >> num; //输入num 14 int sum = getSum(num); //求每一位的和 15 vector<string> ans; //记录sum每一位对应的英文单词 16 do{ //由于可能出现sum为0的情况,所以用do while 17 ans.push_back(str[sum % 10]); 18 sum /= 10; 19 }while(sum); 20 reverse(ans.begin(), ans.end()); //由于记录时时由低位到高位记录,所以将其反转ans 21 for(int i = 0; i < ans.size(); i++){ //输出答案 22 if(i != 0) 23 printf(" "); 24 cout << ans[i]; 25 } 26 return 0; 27 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束