PAT (Advanced Level) Practice 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
思路
- 对于负数,输出一个
Fu
,就可以转换为正数; 对于零,直接输出ling
- 注意输出空格, 解决办法是用
space
来记录是否输出过第一个字段了, 第一个字段无需输出空格, 其他字段需要先输出一个空格, 再正常输出 - 按照(大于1亿,1万-1亿,1万)分为三段, 每段的输出方式是一样的
- 注意像
100800
这样的测试样例, 需要输出800
前的前导零, 但是无需输出800
后面的零, 解决办法是- 对于输出每一个数字的时候,看是不是0, 假如不是零就正常输出就行了,这不可能是前导零了; 假如是零要考虑一下,假如已经是前导零不用动
- 假如不是前导零,而且还不是个位(个位要进入下一段了), 并且还有更高位的非零(这里不是最高位), 那就属于前导零, 把
zero
置为true
AC code
#include<iostream>
#include<string>
using namespace std;
string num[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
string base[4]={"","Shi","Bai","Qian"};
int pow10[9]={1,10,100,1000,10000,100000,1000000,10000000,100000000};
int main(){
int n;
cin>>n;
//处理负号
if(n<0){
cout << "Fu ";
n = -n;
}else if(n==0){
cout << "ling";
return 0;
}
//分成三部分,每部分命名是一样的
int part[3]={n/100000000,(n%100000000)/10000,n%10000};
bool zero = false; //是否输出前导零
bool space = false; //第一个输出的时候无需输出,之后输出空格再输出数字
for(int i=0;i<3;i++){
for(int j=3;j>=0;j--){
int pos = 8-4*i+j;
if(pos>8) continue; //最大到亿
int digit = (part[i]/pow10[j])%10; //取出当前数字
if(digit>0){
//是否要输出ling
if(zero){
zero = false;
if(space) cout<<" ";
else space=true;
cout<<"ling";
}
//输出数字和base
if(j==0){ //个位
if(space) cout<<" ";
else space = true;
cout << num[digit];
}else{
if(space) cout<<" ";
else space = true;
cout << num[digit]<< " " << base[j];
}
}else{ //digit==0,看看要不要输出ling
if(!zero and j!=0 and n/pow10[pos]>=10) zero=true;
}
}
//输出Wan和Yi
if(part[i]>0){
if(i==0) cout<<" Yi";
else if(i==1) cout<<" Wan";
}
}
return 0;
}