华为机试HJ42:学英语
Posted 翟天保Steven
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了华为机试HJ42:学英语相关的知识,希望对你有一定的参考价值。
题目描述:
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
本题含有多组输入数据。
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
示例:
输入:
2356
输出:
two thousand three hundred and fifty six
解题思路:
建立两个字典,分别记录0-19的单词和十倍数的单词。输入数字后,按照其位数从低到高写判断,0-19就直接返回字典里的单词;20-99就先判断是不是正好的十倍数,分情况返回;100-999也分两个情况,如果不是正好的,则返回X百+English(几十);再往上就是千、百万、十亿,特点就是间隔了1000,比如千,就将数据分为多少个1000和几百几十几,百万就分为多少个百万、多少个千和几百几十几,十亿就以此类推。English函数主要通过递归来实现高位数的分析。
测试代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> T19={"zero","one","two","three","four", \\
"five","six","seven","eight","nine",\\
"ten","eleven","twelve","thirteen","fourteen",\\
"fifteen","sixteen","seventeen","eighteen","ninteen"}; // 前二十个数
vector<string> Tenmul={"none","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}; // 十的倍数
string English(int number)
{
if(number>=0&&number<=19)
{
return T19[number];
}
if(number>=20&&number<=99)
{
if(number%10==0)
{
return Tenmul[number/10];
}
return Tenmul[number/10]+" "+English(number%10);
}
if(number>=100&&number<=999)
{
if(number%100==0)
{
return T19[number/100]+" hundred";
}
return T19[number/100]+" hundred and "+English(number%100);
}
if(number>=1000&&number<=999999)
{
if(number%1000==0)
{
return English(number/1000)+" thousand";
}
return English(number/1000)+" thousand "+English(number%1000);
}
if(number>=1000000&&number<=999999999)
{
if(number%1000000==0)
{
return English(number/1000000)+" million";
}
return English(number/1000000)+" million "+English(number%1000000/1000)+" thousand "+English(number%1000);
}
if(number>=1000000000)
{
if(number%1000000000==0)
{
return English(number/1000000000)+" billion";
}
return English(number/1000000000)+" billion "+English(number%1000000000/1000000)+" million "+English(number%1000000/1000)+" thousand "+English(number%1000);
}
return "error";
}
int main()
{
int number;
while(cin>>number)
{
cout<<English(number)<<endl;
}
return 0;
}
以上是关于华为机试HJ42:学英语的主要内容,如果未能解决你的问题,请参考以下文章