PAT甲级 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

思路

将数字按字符串处理,设置下标 left 和 right 来处理数字的一个节(个节、万节、亿节)的输出,left 指向当前需要输出的位,right 指向与 left 同节的个位。

注意点

  • 边界数据 0 的输出应该为 “0“。可以在判断当前位是否是 0 时,加上不为首位这一条件(即若为首位的 0,照常输出)。当然也可以特殊判断输出。
  • 如果万节所有位都为 0,则不能输出多余的万。
#include <cstdio>
#include <cstring>

char num[10][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
char wei[5][5] = {"Shi", "Bai", "Qian", "Wan", "Yi"};

int main() {
    char str[11];
    scanf("%s", str);
    int len = strlen(str), left = 0, right = len - 1;
    if (str[0] == '-') {
        printf("Fu");
        left++;
    }
    while (right - 4 >= left) {
        right -= 4;
    }
    while (left < len) {
        bool flag = false, isPrint = false;
        while (left <= right) {
            if (left > 0 && str[left] == '0') {
                flag = true;
            } else {
                if (flag == true) {
                    printf(" ling");
                    flag = false;
                }
                if (left > 0) {
                    printf(" ");
                }
                printf("%s", num[str[left] - '0']);
                isPrint = true;
                if (left != right) {
                    printf(" %s", wei[right - left - 1]);
                }
            }
            left++;
        }
        if (isPrint == true && right != len - 1) {
            printf(" %s", wei[(len - 1 - right) / 4 + 2]);
        }
        right += 4;
    }
    return 0;
}

文章作者: 吴鑫康
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 吴鑫康 !
评论
  目录