PAT 甲级 1005. Spell It Right (20) C++版

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

用字符串保存输入的数,并将这个树的各个位数进行累加求和,输出这个和的各个位数的英文即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdio>
#include <cstring>
#include <numeric>

char s[][7] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int flag = 0;

void print(int sum) {
if (sum == 0) return;
print(sum / 10);
if (flag) printf(" ");
flag = 1;
printf("%s", s[sum % 10]);
}

int main() {
char s[110];
scanf("%s", s);
int sum = std::accumulate(s, s + strlen(s), 0) - strlen(s) * '0';
if (sum == 0) printf("zero");
else print(sum);
return 0;
}