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;
}
累计访问量: | 昨日访问量: | 昨日爬虫数:
Gunjianpan © 2017 - 2020 Power by VuePress & iofu728/blog