题目描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
方法原型:public static String parse(long num)
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
输入例子:
2356
输出例子:
two thousand three hundred and fifty six
#include <iostream>
#include <string>
using namespace std;
string s1[20] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven","twelve", "thirteen", "fourteen","fifteen","sixteen","seventeen", "eighteen", "nineteen"};
//string s2[10] = {"ten","eleven","twelve", "thirteen", "fourteen","fifteen","sixteen","seventeen", "eighteen", "nineteen"};
string s3[10] ={"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
string lessThan100(long num)
{
string result;
if(num < 20)
result = s1[num-1];
else if (num <100 && num%10 == 0 )
result = s3[num/10-2];
else if (num <100)
result = s3[num/10-2]+" "+s1[num%10-1];
return result;
}
string lessThan1000(long num)
{
string result;
if(num < 100)
result = lessThan100(num);
else if(num%100 == 0)
result = s1[num/100-1] + " hundred";
else
result = (s1[num/100 -1]+" hundred and "+ lessThan100(num%100));
return result;
}
string lessThanMillion(long num)
{
string result;
if(num < 1000)
result = lessThan1000(num);
else if(num % 1000 == 0)
result = lessThan1000(num/1000) + " thousand";
else
result = lessThan1000(num/1000) + " thousand "+ lessThan1000(num%1000);
return result;
}
string lessThanBillion(long num)
{
string result;
if(num <1000000)
result = lessThanMillion(num);
else if(num % 1000000 ==0)
result = lessThanMillion(num/1000000) + " million";
else
result = lessThanMillion(num/1000000) + " million " + lessThanMillion(num%1000000);
return result;
}
string parse(long num)
{
string result;
if(num <= 0 || num >=10000000000)
result = "ERROR";
else if(num < 1000)
result = lessThan1000(num);
else if(num < 1000000)
result = lessThanMillion(num);
else if(num <1000000000)
result = lessThanBillion(num);
else if (num == 1000000000)
result = "one billion";
else
result = s1[num/1000000000-1]+" billion "+ lessThanBillion(num%1000000000);
return result;
}
int main()
{
/*cout << parse(30) << endl;
cout << lessThan1000(15) << endl;
cout << lessThan1000(36) << endl;
cout << lessThan1000(100) << endl;
cout << lessThan1000(909) << endl;
cout << lessThan1000(999) << endl;
cout << lessThanMillion(1000) << endl;
cout << lessThanMillion(1009) << endl;
cout << lessThanMillion(10009) << endl;
cout << lessThanMillion(100009) << endl;
cout << lessThanBillion(1000009) << endl;
cout << lessThanBillion(1009009) << endl;
cout << parse(1000000000) << endl;
cout << parse(1000000009) << endl;*/
long num =0 ;
cin >> num;
cout << parse(num);
return 0;
}