1082 Read Number in Chinese 25 ★★☆

github 地址:https://github.com/iofu728/PAT-A-by-iofu728 难度:★★☆ 关键词:字符串

题目

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

大意

把数字按中文读的方式输出,注意 ling 的读法

思路

  1. 字符串输入,如果带负号,输出Fu,然后去除前缀零;
  2. 字符串从左至右遍历
  • 如果str[0] != '0'则看之前有没有 0(havezero
    • 如果有 0,则输出' ling ' << num[str[0]]
    • 如果没有 0,即!havezero, 则输出num[str[0]]
    • 对当前字符串长度取 4 余length % 4, 如果!= 1,则输出个十百千
  • else, havezero = true
  1. 如果 length == 9 || length == 5 且该段上有非 0 数字出现过(havenum), 则输出万亿

code

#include <iostream>

using namespace std;

string num[10] = {"ling", "yi",  "er", "san", "si",
                  "wu",   "liu", "qi", "ba",  "jiu"};
string unit[6] = {"Qian", "", "Shi", "Bai"};
string units[3] = {"", "Wan", "Yi"};

int main(int argc, char const *argv[]) {
  string str;
  bool havezero = false;
  bool havenum = true;
  getline(cin, str);
  if (str[0] == '-') {
    str = str.substr(1);
    cout << "Fu ";
  }
  while (str[0] == '0') str = str.substr(1);
  if (!str.length()) {
    cout << "ling";
    return 0;
  }
  int totallength = str.length();
  while (str.length()) {
    int length = str.length();
    if (str[0] != '0') {
      if (havezero) cout << " ling";
      if (totallength != length) cout << ' ';
      cout << num[str[0] - '0'];
      if (length % 4 != 1) cout << ' ' << unit[length % 4];
      havenum = true;
    } else {
      havezero = true;
    }
    if (length == 9 || length == 5) {
      if (havenum) {
        cout << ' ' << units[length / 4];
        havezero = false;
      }
      havenum = false;
    }
    str = str.substr(1);
  }

  return 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
You can use this BibTex to reference this blog if you find it useful and want to quote it.