PAT甲级——A1082 Read Number in Chinese

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 #include <vector>
 4 using namespace std;
 5 string num[10] = { "ling","yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu" };
 6 string c[6] = { "Ge","Shi", "Bai", "Qian", "Yi", "Wan" };
 7 int J[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
 8 vector<string> res;
 9 int main() {
10     int n;
11     cin >> n;
12     if (n == 0) {
13         cout << "ling";
14         return 0;
15     }
16     if (n < 0) {
17         cout << "Fu ";
18         n = -n;
19     }
20     int part[3];
21     part[0] = n / 100000000;
22     part[1] = (n % 100000000) / 10000;
23     part[2] = n % 10000;
24     bool zero = false; //是否在非零数字前输出合适的ling
25     int printCnt = 0; //用于维护单词前没有空格,之后输入的单词都在前面加一个空格。
26     for (int i = 0; i < 3; i++) {
27         int temp = part[i]; //三个部分,每部分内部的命名规则都一样,都是X千X百X十X
28         for (int j = 3; j >= 0; j--) {
29             int curPos = 8 - i * 4 + j; //当前数字的位置
30             if (curPos >= 9) continue; //最多九位数
31             int cur = (temp / J[j]) % 10;//取出当前数字
32             if (cur != 0) {
33                 if (zero) {
34                     printCnt++ == 0 ? cout << "ling" : cout << " ling";
35                     zero = false;
36                 }
37                 if (j == 0)
38                     printCnt++ == 0 ? cout << num[cur] : cout << ' ' << num[cur]; //在个位,直接输出
39                 else
40                     printCnt++ == 0 ? cout << num[cur] << ' ' << c[j] : cout << ' ' << num[cur] << ' ' << c[j]; //在其他位,还要输出十百千
41             }
42             else {
43                 if (!zero&&j != 0 && n / J[curPos] >= 10) zero = true;   //注意100020这样的情况
44             }
45         }
46         if (i != 2 && part[i] > 0) cout << ' ' << c[i + 4]; //处理完每部分之后,最后输出单位,Yi/Wan
47     }
48     return 0;
49 }

声明:该文章系转载,转载该文章的目的在于更广泛的传递信息,并不代表本网站赞同其观点,文章内容仅供参考。

本站是一个个人学习和交流平台,网站上部分文章为网站管理员和网友从相关媒体转载而来,并不用于任何商业目的,内容为作者个人观点, 并不代表本网站赞同其观点和对其真实性负责。

我们已经尽可能的对作者和来源进行了通告,但是可能由于能力有限或疏忽,导致作者和来源有误,亦可能您并不期望您的作品在我们的网站上发布。我们为这些问题向您致歉,如果您在我站上发现此类问题,请及时联系我们,我们将根据您的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。