华为-学英语

(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();   //去掉尾部空格
    }
}












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值