PAT 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.
解答:這道題我剛開始的解法是:對資料從低位開始,每四位進行劃分,然後分別求解,過程相當複雜,而且有一個用例過不了。
後來我借鑑了一位博主的思路,先對特殊情況進行判定,然後用棧從低位開始處理,每位的權重用陣列表示,最終得到結果,這是我遇到的最好的答案了。
不過他對特殊情況的判定只有0,然而如果是100000000,會將最後的Wan輸入,雖然測試用例過了,但補充下演算法更完整。
AC程式碼如下:
#include<iostream> #include<string> #include<stack> #include<cstdlib> using namespace std; char digit[10][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"}; char weight[10][5] = {"", "Shi", "Bai", "Qian", "Wan", "Shi", "Bai", "Qian", "Yi"}; int main() { string n; cin >> n; //特殊情況0和100000000 if(n.size() == 1 && n[0] - '0' == 0){ printf("%s\n", digit[0]); return 0; } if(n.size() == 9 && atoi(n.c_str()) == 100000000){ printf("yi Yi\n"); return 0; } if(n[0] == '-'){ printf("Fu "); n.erase(0, 1); } stack<string> sta; int zeroFlag = 0; for(int i = n.size() - 1, j = 0; i >= 0; --i, j++){ if(n[i] == '0'){ if( zeroFlag == 1 && n[i+1] != '0' ){ sta.push(digit[0]); zeroFlag = 0; } if( j == 4 ){ sta.push(weight[j]); } } else{ if(j != 0) //只有j != 0時才將權重加入 sta.push(weight[j]); sta.push(digit[n[i] - '0']); zeroFlag = 1; } } //輸出結果 int first = 1; while(!sta.empty()){ if(first == 1){ cout << sta.top(); first = 0; } else{ cout << " " << sta.top(); } sta.pop(); } return 0; }