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 • 1
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; }