将数字翻译成英文


public class Demo {

/*
* Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
* 如22: twenty two ,123:one hundred and twenty three。
*
* 注意事项:
* 1、数字为正整数,长度不超过十位,不考虑小数,转化结果为英文小写;
* 2、输出格式为twenty two;
* 3、非法数据请返回“error”;
* 4、关键词提示:and, billion,million, thousand, hundred 。
*
* 输入参数:
* long num 输入的数字,如1234
* 返回值:
* 正常情况下返回数字对应的英文,如one thousand two hundred and thirty four
*/
public static String parse(long num) {
if(num >= 10000000000L || num < 0L){
return "error";
}
StringBuffer sb = new StringBuffer();
if(num >= 1000000000L){
sb.append(subParse1(num / 1000000000L));
sb.append(" billion");
if(num / 1000000000L > 1){
sb.append("s");
}
num = num % 1000000000L;
}
if(num >= 1000000L){
if(!sb.toString().equals("")){
sb.append(" ");
}
sb.append(subParse1(num / 1000000L));
sb.append(" million");
if(num / 1000000L > 1){
sb.append("s");
}
num = num % 1000000L;
}
if(num >= 1000L){
if(!sb.toString().equals("")){
sb.append(" ");
}
sb.append(subParse1(num / 1000L));
sb.append(" thousand");
if(num / 1000L > 1){
sb.append("s");
}
num = num % 1000L;
}
if(num > 0){
if(!sb.toString().equals("")){
sb.append(" ");
}
sb.append(subParse1(num));
}else{
if(sb.toString().equals("")){
sb.append("zero");
}
}
return sb.toString().trim();
}
/**
* 个数最多只有三位的读法
* @param num
* @return
*/
public static String subParse1(long num){
Integer i = (int) num;

String[] str0to19 = new String[]{
"zero","one","two","three","four","five",
"six","seven","eight","nine","ten",
"eleven","twelve","thirteen","fourteen","fifteen",
"sixteen","seventeen","eighteen","nineteen"
};
String[] str20to90 = new String[]{
"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"
};
StringBuffer result = new StringBuffer();
if(i >= 100){
result.append(str0to19[i/100]);
result.append(" hundred");
if(i / 100 > 1){
result.append("s");
}
i = i % 100;
}

if(i >= 20){
if(!result.toString().equals("")){
result.append(" and ");
}
result.append(str20to90[i/10 - 2]);
if(i % 10 != 0){
result.append(" " + str0to19[i % 10]);
}
}else if(i > 0){
if(!result.toString().equals("")){
result.append(" and ");
}
result.append(str0to19[i]);
}
return result.toString().trim();
}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值