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
题意:给出一个不超过9位的数字,让你按汉语的习惯输出数字的发音。注意:
①如果某个非零数字前面有零,则要输出零,例如8080,输出:ba Qian ling ba Shi。如8008,输出:ba qian ling ba。如10808,输出:yi wan ling ba bai ling ba。
②每一节末尾要对应输出wan或yi,个位除外。
思路:1.使用双指针left(0)和right(n-1)标记一节(个节,万节,亿节)的位置,初始情况,令right不断-4,直到left+4超过right为止。
2.对于每一节的数字,使用flag标记是否有累计的零。如果有则先输出:” ling“。另外如果是首位为0(输入只有一个0),则不输出累计的0。然后再输出对应数字和单位,每输出一节后输出对应节的单位,注意,如果某节没有输出数字,则不输出节的单位,如800000008。输出:“ba yi ling ba”。
参考代码:
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
string digit[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
string unit[]={"Shi","Bai","Qian","Wan","Yi"};
int main()
{
string s;
getline(cin,s);
int n=s.size(),left=0,right=s.size()-1;
if(s[0]=='-') {
cout<<"Fu";
left++;
}
while(left+4<=right) right-=4;
while(left<n){
bool flag=false; //标记有没有累计的0
bool isPrint=false; //标记当前节有没有输出
while(left<=right){ //循环处理一节
if(left>0&&s[left]=='0') //标记累积的0,并且0不是首位
flag=true;
else {
if(flag) cout<<" ling"; //每次输出数字前判断是否有累计的0
flag=false;
if(left>0) cout<<" ";
cout<<digit[s[left]-'0'];
isPrint=true;
if(left!=right) //某节中,除个位以外都要输出对应的单位
cout<<" "<<unit[right-left-1];
}
left++;
}
if(isPrint&&right!=n-1)
cout<<" "<<unit[(n-1-right)/4+2]; //输出一节的单位
right+=4;
}
return 0;
}