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
本题本身难度不大,但是要把所有情况考虑到比较困难,提供一些测试用例:
/*
-800000008
123400000
120000000
8080808
23000010
0
*/
这是我的代码,在转换字符的时候,就控制格式,还有一别人的代码,是在转换完毕后,再控制输出格式。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string num[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
string jinwei[6]={"","Shi","Bai","Qian","Wan","Yi"};
vector<string> out;
void changetos(int n){
int k=0;
bool first0=true,get0=false;//判断是否为首位0,连续0
while(n!=0){
for(int i=0;i<=3;i++){
int t=n%10;
if(t==0)
{
if(!first0&&!get0){
out.push_back(num[t]);
}
get0=true;
}
else{
if(i!=0){
out.push_back(num[t]+" "+jinwei[i]);
}
else out.push_back(num[t]);
get0=false;
first0=false;
}
n/=10;
if(n==0) break;
k++;
if(k==4||k==8) {//判断是否是万位或亿位
if(k==8&&out[out.size()-1]=="Wan")
out.erase(out.end()-1);
out.push_back(jinwei[4+k/8]);first0=true;//重置首位0
}
}
}
}
int main(){
freopen("in.txt","r",stdin);
int n;
cin>>n;
if(n<0) {
cout<<"Fu ";
n=-n;
}
if(n){
changetos(n);
for(int i=out.size()-1;i>0;i--){
cout<<out[i]<<" ";
}
cout<<out[0];
}
else cout<<num[0];
return 0;
}
感谢小5555的分享。
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
string a[] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
string b[] = {"", "Shi", "Bai", "Qian", "Wan", "Shi", "Bai", "Qian", "Yi"};
vector<string> res;
vector<int> digit;
int num, e;
cin >> num;
if (num == 0){
cout << "ling";
return 0;
}
else if (num < 0){
cout << "Fu ";
num = -num;
}
while (num != 0){
digit.push_back(num%10);
num /= 10;
}
for (e=0; e<digit.size() && digit[e]==0; ++ e) {}
if (e == 8){
cout << a[digit[e]] << " Yi";
return 0;
}
for (int i = e; i < digit.size(); ++ i){
if (i!=0 && (digit[i]!=0 || i==4 || i==8)){
res.push_back( b[i] );
}
res.push_back(a[ digit[i] ]);
}
for (int i = res.size()-1; i >= 0; -- i){
if (i != res.size()-1){
cout << " ";
}
int cnt = 0;
while (i>=0 && res[i]=="ling"){
-- i;
++ cnt;
}
if (cnt!=0 && res[i]!="Wan"){
cout << "ling ";
}
cout << res[i];
}
return 0;
}