PAT甲級真題 1082 Read Number in Chinese (25分) C++實現(中文讀數,分治法)

題目

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

思路

很噁心的一道題,需要手動判斷各種情況。

將數字分成3部分:p3億p2萬p1,每個部分的轉換規則是相同的,問題就簡化爲4位數字的讀法轉換。

用函數printNum(int p)分別打印各個部分,處理的數字可能包含“千百十個”共四位。讀“ling”的判斷依據是:該位爲百位或十位時,該位爲0但高位不全爲0。

代碼

#include <iostream>
using namespace std;

string s[] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
void printNum(int p){
    int qian = p / 1000;
    int bai = p % 1000 / 100;
    int shi = p % 100 / 10;
    int ge = p % 10;
    if (qian > 0){
        cout << s[qian] << " Qian";
    }
    if (bai > 0){
        if (qian>0){
            cout << " ";
        }
        cout << s[bai] << " Bai";
    }
    else if (qian>0 && (ge>0||shi>0)){
        cout << " ling";
    }
    if (shi > 0){
        if (qian>0 || bai>0){
            cout << " ";
        }
        cout << s[shi] << " Shi";
    }
    else if ((qian>0||bai>0) && ge>0){
        cout << " ling";
    }
    if (ge > 0){
        if (qian>0 || bai>0 || shi>0){
            cout << " ";
        }
        cout << s[ge];
    }
}
int main(){
    long long n;
    cin >> n;
    if (n == 0){
        cout << "ling";
        return 0;
    }
    if (n < 0){
        n = -n;
        cout << "Fu ";
    }
    int p1 = n / 100000000;
    int p2 = n / 10000 % 10000;
    int p3 = n % 10000;
    if (p1 != 0){
        printNum(p1);
        cout << " Yi";
    }
    if (p2 != 0){
        if (p1!=0){
            cout << " ";
            if (p2 < 1000){
                cout << "ling ";
            }
        }
        printNum(p2);
        cout << " Wan";
    }
    if (p3 != 0){
        if(p1!=0 || p2!=0){
            cout << " ";
            if (p3 < 1000){
                cout << "ling ";
            }
        }
        printNum(p3);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章