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;
}