A1082 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

思路:

• 设置下标left和right,分别指向一小节(4位或者小于4位)的当前位和个位;

• 循环处理每一小节的数据,当遇到非第一位的0的时候,flag=1;如果不是0,判断前面是否已经累积0决定是和否输出“ling”,然后依次输出汉语和位数;

• 在每一小节输出之后判断是否输出“Wan”或“Yi”。注意大小写,被“Fu”写成“fu”搞得心力交瘁(╬ ̄皿 ̄)=○

以上思路参照《算法笔记》和我自己的理解。

 

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int n;
    string s;
    string hy[10] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
    string wei[3] = { "Shi","Bai","Qian" };
    string sw[2] = { "Wan","Yi" };
    cin >> n;
    if (n == 0)cout << "ling";
    else {
        if (n < 0)cout << "Fu" << " ";
        s = to_string(abs(n));
    }
    int len = s.length();
    int left = 0, right = len - 1;//分别指向首尾元素
    while (left + 4 <= right)
        right -= 4;

    while (left < len) {
        int flag = 0;//是否有累积0
        int isprint = 0;//是否已经有输出
        while (left <= right) {
            if (s[left] == '0') {
                flag = 1;
            }
            else {
                if (left > 0)cout << " ";
                if (flag == 1) {
                    cout << "ling" << " ";
                    flag = 0;
                }
                cout << hy[s[left] - '0'];
                isprint = 1;
                if (left != right)cout << " " << wei[right - left - 1];
            }
            left++;
        }

        if (isprint == 1 && right != len - 1) {
            cout << " " << sw[(len-right)/4-1];
        }
        right += 4;
    }

    return 0;
}

 

posted @ 2020-02-13 16:47  PennyXia  阅读(175)  评论(0编辑  收藏  举报