pat A 1082.Read Number in Chinese
用中文方式读取整数型数字
大三小菜鸡一枚,最近在刷pat题目相当吃力,想记录一下自己每天的学习情况,将自己的经验和教训和大家分享一下,也希望能得到诸多大神的指点谢谢!第一次发博客请多多指教鸭!
题目描述
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”.
输入格式
Each input file contains one test case, which gives an integer with no more than 9 digits.
输出格式
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.
输入样例1
-123456789
输出样例1
Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu
输入样例2
100800
输出样例2
yi Shi Wan ling ba Bai
思路
在算法宝典样例中输入为一个字符串数组,题目中说数字绝对值大小小于10^10,因此也可以考虑用整型输入并用整型数组进行存储每一位(但影响不大反而不具有普遍性我就是这么整的不想改了)。如果是零直接输出零,如果是复数取其相反数,对每一位数取模得到每一位,并记录数组的长度。
用count记录该数字之前零出现的个数,对每一位数,分为三类讨论:
1.该位为0,0的个数加一。
2.不为0,该数前面没有0,将该位输出。
3.不为0,该数前面有0,输出ling和该位数,将0的个数归零。
同时对每一位数进行讨论,如果该数对4取模为0,并且该数前面0的数量不为4(由于该数大小小于10^10,不需要对亿及其以上位讨论),将“Yi Wan”输出,否则不输出“Wan”;如果对4取模为3,2或1并且该位数不为0,输出“Qian Bai Shi”。
注意判断输入空格的条件,这里用一个函数来进行判断。
源代码
#include<cstdio>
char Chinese[9][10]={"yi","er","san","si","wu","liu","qi","ba","jiu"};
char e1[2][10]={"Yi","Wan"};
char e2[3][10]={"Shi","Bai","Qian"};
void judge(int i)//判断输出空格的条件
{
if(i)
{
printf(" ");
}
}
int main()
{
int x;
int m;
int count=0;
scanf("%d",&x);
if(x<0)//对复数取反
{
printf("Fu ");
x=-x;
}
if(x==0)
{
printf("Ling");
}
int num[100];
int len=0;
while(x)//存储每一位数和总长度
{
num[len++]=x%10;
x/=10;
}
for(int i=len-1;i>=0;i--)
{//判断每位数字的情况
if(num[i]==0)//该位数为零
{
count++;
}
else if(num[i]!=0&&count==0)//不为零该数前面也没有零
{
printf("%s",Chinese[num[i]-1]);/
judge(i);
}
else if(num[i]!=0&&count!=0)//不为零该数前面有零
{
printf("ling %s",Chinese[num[i]-1]);//将零在前面输出
count=0;
judge(i);
}
//对每四位数取模判断位输出
if(i%4==0&&count!=4)
{
m=2-i/4;
printf("%s",e1[m]);
judge(i);
}
else if((i%4==3||i%4==2||i%4==1)&&num[i]!=0)
{
printf("%s",e2[i%4-1]);
judge(i);
}
}
return 0;
}
样例结果
总结
这种方法相对比较暴力,而书上的移位方式比较巧妙,对于我这等菜鸟来说这种方法更容易想到,但是移位的方法也是一定要掌握滴!