题目描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
#include<iostream>
//#include<vector>
//#include<algorithm>
using namespace std;
string num1[] = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
string num2[] = {"ten","eleven","twelve","thirteen","fourteen",
"fifteen","sixteen","seventeen","eighteen","nineteen"};
string num3[] = {"twenty","thirty","forty","fifty",
"sixty","seventy","eighty","ninety"};
string translate(long);
string Parse(long num)
{//把数字以3位数为单位进行切分
string res="";
long billion = num / 1000000000;//十亿部分
if(billion != 0){
res.append(translate(billion) + " billion ");//翻译十亿部分
}
num = num % 1000000000;//百万部分
long million = num / 1000000;
if(million != 0){
res.append(translate(million) + " million ");//翻译百万部分
}
num = num % 1000000;//千部分
long thousand = num / 1000;
if(thousand != 0){
res.append(translate(thousand) + " thousand ");//翻译千部分
}
num = num % 1000;//百部分
if(num != 0){
res.append(translate(num));//翻译百部分
}
int len=res.size();//去除字符串后面的空格
if(res[len-1]==' ') res.resize(len-1);
return res;
}
string translate(long num)
{//处理三位数
string s="";
long h = num / 100;//百位处理
if(h != 0){
s.append(num1[(int) h] + " hundred");
}
num = num % 100;//十位部分
long k = num / 10;
if(k != 0){
if(h != 0)//如果有百位别忘了加and
s.append(" and ");
if(k == 1){//若十位为1,连同个位一起翻译
long t = num % 10;
s.append(num2[(int)t]);
}
else{//否则,十位和个位分别单独翻译
s.append(num3[(int)k - 2] + " ");
if(num % 10 != 0)
s.append(num1[(int)(num % 10)]);
}
}
else if(num % 10 != 0){//如果没有十位部分,直接翻译个位部分
if(h != 0)
s.append(" and ");
s.append(num1[(int)(num % 10)]);
}
int len=s.size();//去除字符串后面的空格
if(s[len-1]==' ') s.resize(len-1);
return s;
}
int main()
{
long num;
while(cin>>num){
cout<<Parse(num)<<endl;
}
return 0;
}