PAT Advanced 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

算法描述:模拟

题目大意:

给出一个不超过9位的阿拉伯数字,输出其中文读法

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
// 从后往前4位为一节
char num[10][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
int digit[10];
vector<string> ans;

int main()
{
    int n;
    cin >> n;
    if(n == 0){cout << "ling"; return 0;}   
    if(n < 0)    ans.push_back("Fu"), n *= -1;
    
    string s = to_string(n);
    for(int i = 0 ; i < s.size() ; i ++)
        digit[s.size() - 1 - i] = s[i] - '0';
    //①插零(前插) ②存本位数字 ③存储单位 
    for(int i = s.size() - 1 ; i >= 0 ; i --)
    {
        //插零操作(前插)  当前位不是最高位且不为0时,有两种情况需要前插ling ①当前位非每一节最高位 ②当前位的上一节全部为0
        if(i != s.size() - 1 && digit[i] > 0) //不是最高位 且 不为0 检查是否需要读入ling
        {
            if(i % 4 != 3) // 千万 和 千 的前面不需要加ling  
                if(digit[i + 1] == 0)   ans.push_back("ling");
            else{
                if(!digit[i + 4] && !digit[i + 3] && !digit[i + 2] && !digit[i + 1]) // 上一节全部为0 如100002345 读到2时需要在前面加ling
                    ans.push_back("ling");
            }
        }
        
        if(digit[i] > 0)    ans.push_back(num[digit[i]]); // 先存本位数字
        // 再判断单位
        if(i == 8)  ans.push_back("Yi"); // 最多9位  如果能从亿位开始遍历则不需要判断直接放入"Yi"
        else if(i == 4){ 
            if(digit[4] || digit[5] || digit[6] || digit[7]) // 万为单位的一节有非零数
                ans.push_back("Wan");
        }
        else{
            if(digit[i] && i % 4 == 3)  ans.push_back("Qian");
            else if(digit[i] && i % 4 == 2) ans.push_back("Bai");
            else if(digit[i] && i % 4 == 1) ans.push_back("Shi");
        }
    }
    
    for(int i = 0 ; i < ans.size() ; i ++)
    {
        if(i)   cout << ' ';
        cout << ans[i];
    }
    return 0;
}
posted @ 2022-08-19 23:25  D_coding_blog  阅读(19)  评论(0)    收藏  举报