【PAT甲级A1082】Read Number in Chinese (25分)(c++)

1082 Read Number in Chinese (25分)

作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:250 ms
内存限制:64 MB

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

题意:

将所给数字用中文读法方法输出。

思路:

设当前所在位数为len,如千位,len=4,百位,len=3…中文读法的规律为:
1.只有当前位不为0,且上一位为0,需要读零。(如果输入为0,则为特殊情况需要分类)
2.当前位不是0,则读这位数,且当len%4=1,读十,len%4=2,读百,len%4=3读千。
4.当前位不管是不是0,当len%4=0,若len/4=0,是个为,不读位号,若len/4=1,读万,若len/4=2,读亿。

参考代码:

#include <iostream>
#include <string>

using namespace std;
char unit[5][5] = {" ", "Shi", "Bai", "Qian"};
char unit2[3][5] = {" ", "Wan", "Yi"};
char number[10][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};

int main() {
    string str;
    cin >> str;
    if (str == "0") {
        printf("ling");
        return 0;
    }
    if (str[0] == '-') {
        printf("Fu ");
        str.erase(0, 1);
    }
    int len = str.length() - 1;
    for (int i = 0; i < str.length(); i++, len--) {
        if (i > 0 && str[i] != '0' && str[i - 1] == '0')printf(" ling");
        if (str[i] != '0') {
            if (i != 0)printf(" ");
            printf("%s", number[str[i] - '0']);
            if (len % 4 != 0)printf(" %s", unit[len % 4]);
        }
        if (len % 4 == 0 && len / 4 != 0)printf(" %s", unit2[len / 4]);
    }
    return 0;
}

如有错误,欢迎指正

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值