✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1005 Spell It Right (pintia.cn)
🔑中文翻译:拼写正确
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1005 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 (≤10100).
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
思路
- 用字符串
x
读入数字,然后计算每一位数的总和。注意,这里有个小技巧,计算字符串的每一位数可以通过i - '0'
来求。 - 将要用到的单词用数组存起来,就不用反复
if else
了。 - 对总和
sum
进行字符串转化得到res
,然后对res
从前往后遍历,将数字转换成对应的单词并输出。这里同样要注意的是,在PAT
中,对于输出的空格把控很严格,行尾不能有多余空格。所以我们可以先输出一个答案,然后再对后续答案进行统一化输出。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string x;
cin >> x;
//计算每一位数的总和
int sum = 0;
for (auto i : x) sum += i - '0';
//将字符串用数组存起来,方便使用
string words[10] = { "zero","one","two","three"
,"four","five","six","seven","eight","nine" };
//将结果进行字母转换
string res = to_string(sum);
cout << words[res[0] - '0'];
for (int i = 1; i < res.size(); i++)
cout << " " << words[res[i] - '0'];
return 0;
}