【PAT-Advanced】1005 Spell It Right

Problem

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 (≤10^{100})$.

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



Solution

还挺简单。

要注意的是两个点

  1. 大数。最大可能是100位,所以读入的时候要用string而不是int
  2. 输入是0的时候

实现代码如下

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;

string input;
string output = "";
int sum = 0;

void trans(int num){
if(output != ""){
output = " " + output;
}
switch (num){
case 1:
output = "one" + output;
break;
case 2:
output = "two" + output;
break;
case 3:
output = "three" + output;
break;
case 4:
output = "four" + output;
break;
case 5:
output = "five" + output;
break;
case 6:
output = "six" + output;
break;
case 7:
output = "seven" + output;
break;
case 8:
output = "eight" + output;
break;
case 9:
output = "nine" + output;
break;
case 0:
output = "zero" + output;
break;
}
}

int main(int argc, const char * argv[]) {
cin >> input;
int length = input.length();
while(length--){
sum += input[0] - '0';
input = input.substr(1, length+1);
}
if(sum == 0){
output = "zero";
}
while(sum){
trans(sum % 10);
sum /= 10;
}
cout << output << endl;
return 0;
}