1082.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

思路

题目显示了不超过九位数,因此每个位置的数字的单位是固定的(有一种情况除外,下面会提及),所以可以将数字和单位都存入数组中。
首先考虑0和负数的情况,如果是0直接处理即可;如果是负数则先输出Fu之后再取相反数赋值给字符串。
遍历字符串,如果非0,首先判断前方是否有0,有则多输出一个ling,否则直接输出相应的数字以及单位。如果为0则把hasz标记标1。
特殊情况是,如果是万级别以上的数字,不论有多少个0,再万级结束以后都会输出Wan,这里需要多加一个判断。

代码

#include <iostream>
#include <string>
using namespace std;
string num[10] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
string unit[9] = { "Fu","Shi","Bai","Qian","Wan","Shi","Bai","Qian","Yi" };
int main() {
    int c, hasz = 0, isfirst=1;
    cin >> c;
    if (c == 0) {
        cout << "ling";
        return 0;
    }
    string s;
    if (c < 0) {
        cout << "Fu ";
        c = -c;
    }
    s = to_string(c);
    for (int i = 0; i <s.size(); i++) {
        //if not zero
        if (s[i] != '0') {
            if (hasz) {
                cout << (isfirst == 1 ? "" : " ") << "ling";
                hasz = 0;
            }
            cout << (isfirst == 1 ? "" : " ") << num[s[i] - '0'];
            if (i != s.size() - 1) cout << " " << unit[s.size() - i - 1];
            isfirst = 0;
        }
        else {
            if (s.size() - i - 1 == 4) cout << " " << unit[s.size() - i - 1];
            hasz = 1;
        }
    }
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容