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

我的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>

//解题思路:
//1.通过字符串数组保存单词,下标与词义对应
//2.递归打印sum,打印时输出与其对应的单词

using namespace std;

//单词数组
const char *words[] = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};

void _printByWords(int num)
{
if (num) {
_printByWords(num / 10);
cout << words[num % 10] << " ";
}
}

//以单词形式打印num
void printByWords(int num)
{
//这样调用仅仅为了控制格式
_printByWords(num / 10);
cout << words[num % 10];
}

int main()
{
string num;
int sum = 0;

cin >> num;
//累加每一个数的和
for (const auto x : num) {
sum += x - '0';
}

printByWords(sum);
cout << endl;

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/8241a5d8/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏