华为-学英语
(java实现)
问题描述:
题目描述
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
本题含有多组输入数据。
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
示例1
输入
2356
输出
two thousand three hundred and fifty six
问题分析:
算法实现:
略
参考代码:
import java.util.*;
public class Main {
//个位数
public static String[] num1 = {"zero","one","two","three","four","five","six","seven","eight","nine"};
//十位数
public static String[] num2 = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
//11-19
public static String[] num3 = {"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while (input.hasNext())
{
long num = input.nextLong();
System.out.println(parse(num));
}
input.close();
}
public static String parse(long num)
{
if (num<0)
return "error";
StringBuilder res = new StringBuilder();
long billion = num/1000000000; //处理亿万
if (billion != 0)
{
res.append(trans(billion) + " billion ");
}
num %= 1000000000;
long million = num/1000000; //处理百万
if (million != 0)
{
res.append(trans(million) + " million ");
}
num %= 1000000;
long thousand = num/1000; //处理千
if (thousand != 0)
{
res.append(trans(thousand) + " thousand ");
}
num %= 1000; //处理剩下1000
if (num != 0)
{
res.append(trans(num));
}
return res.toString().trim(); //去掉尾部空格
}
public static String trans(long num)
{
StringBuilder res = new StringBuilder();
long h = num/100;
if(h != 0)
{
res.append(num1[(int)h] + " hundred ");
}
num %= 100;
if (h != 0)
{
res.append("and "); //百位不为0
}
if (num>=20)
{
//处理十位
res.append(num2[(int)num/10-2]);
//处理个位
if (num%10 != 0)
{
res.append(" "+ num1[(int)num%10]);
}
}else if(num>=10 && num<20)
{
res.append(num3[(int)num-10]);
}else
{
res.append(num1[(int)num]);
}
return res.toString().trim(); //去掉尾部空格
}
}