题目描述
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
求解思路
- 处理0和-0的特殊情况
- 将负数转换成正数处理
- 正数长度为1-4的情况
- 正数长度为5-8的情况
- 处理0~len-5的字符
- 处理len-4~len-1的字符
- 正数长度为9的情况
- 处理0位字符
- 处理1-4位字符
- 处理5-8位字符
代码实现(AC)
#include<cstring>
#include<string>
char English2C[11][10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
char s[11][8]={"absent","Shi","Bai","Qian"};
int len=0;
char str[20];
bool is_Special(char str[]) //特殊情况
{
bool flag=false;
int len=strlen(str);
if((len==2&&str[0]=='-'&&str[1]=='0')||(len==1&&str[0]=='0'))
{
printf("ling");
flag=true;
}
return flag;
}
bool is_not0(char str[],int start,int end) //判断某段字符是否为 非全零
{
for(int i=start;i<=end;i++)
{
if(str[i]!='0') return true;
}
return false;
}
bool print(char str[],int start,int end,int num) //打印某段字符
{
bool flag=false;
for(int i=start;i<=end;i++)
{
int tmp=len-1-i;
if(str[i]!='0')
{
num++;
flag=true;
if(num!=1)
printf(" ");
printf("%s",English2C[str[i]-'0']);
if(tmp%4!=0)
printf(" %s",s[tmp%4]);
}
else if(flag==true&&i-1>=0&&str[i-1]!='0'&&is_not0(str,i,end))
printf(" ling");
}
return flag;
}
int main()
{
scanf("%s",str);
len=strlen(str);
if(is_Special(str))
return 0;
if(str[0]=='-') //对负数进行预处理
{
printf("Fu ");
for(int i=1;i<len;i++)
str[i-1]=str[i];
len--;
}
/*处理正字符长度为1-4的情况*/
if(len>=1&&len<=4)
print(str,0,len-1,0);
else if(len>=5&&len<=8)
{
bool t=print(str,0,len-5,0);
if(t) printf(" Wan");
if(t&&str[len-4]=='0'&&str[len-5]=='0'&&is_not0(str,len-4,len-1))
printf(" ling");
if(is_not0(str,len-4,len-1))
printf(" ");
print(str,len-4,len-1,0);
}
else if(len==9)
{
if(str[0]!='0')
{
printf("%s ",English2C[str[0]-'0']);
printf("Yi");
}
if(str[0]!='0'&&str[1]=='0'&&is_not0(str,1,4))
printf(" ling");
if(is_not0(str,1,4))
printf(" ");
bool t=print(str,1,4,0);
if(t)
printf(" Wan");
else if(str[0]!='0'&&is_not0(str,5,8))
printf(" ling");
if(is_not0(str,5,8))
printf(" ");
print(str,5,8,0);
}
return 0;
}