PAT 1082. Read Number in Chinese (25)

1082. Read Number in Chinese (25)

Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese way. Output "Fu" first if it is negative. For example, -123456789 is read as "Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu". Note: zero ("ling") must be handled correctly according to the Chinese tradition. For example, 100800 is "yi Shi Wan ling ba Bai".

Input Specification:

Each input file contains one test case, which gives an integer with no more than 9 digits.

Output Specification:

For each test case, print in a line the Chinese way of reading the number. The characters are separated by a space and there must be no extra space at the end of the line.

Sample Input 1:
-123456789
Sample Output 1:
Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu
Sample Input 2:
100800
Sample Output 2:
yi Shi Wan ling ba Bai

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 string ToChinese(string s)
 7 {
 8     string chinese[20]{"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
 9     s = string(4 - s.size(), '0') + s;
10     string res;
11 
12     if (s[0] != '0')
13     {
14         res += (chinese[s[0] - '0']) + " Qian";
15         if (s.substr(1, 3) != "000")
16         {
17             if (s.substr(1, 1) == "0")
18                 res += " ling";
19             res += (" " + ToChinese(s.substr(1, 3)));
20         }
21     }
22     else if (s[1] != '0')
23     {
24         res += (chinese[s[1] - '0']) + " Bai";
25         if (s.substr(2, 2) != "00")
26         {
27             if (s.substr(2, 1) == "0")
28                 res += " ling";
29             res += (" " + ToChinese(s.substr(2, 2)));
30         }
31     }
32     else if (s[2] != '0')
33     {
34         res += (chinese[s[2] - '0']) + " Shi";
35         if (s.substr(3, 1) != "0")
36             res += (" " + ToChinese(s.substr(3, 1)));
37     }
38     else
39         res += chinese[s[3] - '0'];
40     
41     return res;
42 }
43 
44 int main()
45 {
46     string s;
47     cin >> s;
48     if (s[0] == '-')
49     {
50         cout << "Fu" << " ";
51         s.erase(s.begin());
52     }
53     if (s.size() > 8)
54     {
55         cout << ToChinese(s.substr(0, s.size() - 8)) << " Yi";
56         s = s.substr(s.size() - 8, 8);
57         if (s != "00000000")
58             cout << " ";
59         else
60             return 0;
61         if (s[0] == '0')
62             cout << "ling ";
63     }
64     if (s.size() > 4)
65     {
66         cout << ToChinese(s.substr(0, s.size() - 4)) << " Wan";
67         s = s.substr(s.size() - 4, 4);
68         if (s != "0000")
69             cout << " ";
70         else
71             return 0;
72         if (s[0] == '0')
73             cout << "ling ";
74     }
75     cout << ToChinese(s);
76 }

 

posted @ 2015-08-15 23:00  JackWang822  阅读(207)  评论(0编辑  收藏  举报