学英语

题目描述:

Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:

如22:twenty two,123:one hundred and twenty three。

说明:

数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;

输出格式为twenty two;

非法数据请返回“error“;

输入描述:

输入一个long型整数

输出描述:

输出相应的英文写法

思路:

每3位处理一次,并对3位进行翻译

import java.util.Scanner;

public class Main
{
    public static String[] arr1 = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    public static String[] arr2 = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    public static String[] arr3 = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            long num = scanner.nextLong();
            System.out.println(convert(num));
        }
    }
    public static String convert(Long num)
    {
        String res = "";
        if (num < 0) return "error";
        long billion = num / 1000000000;
        num = num % 1000000000;
        long million = num / 1000000;
        num = num % 1000000;
        long thousand = num / 1000;
        num = num % 1000;
        if (billion != 0)
            res += converHelp(billion) + " billion";
        if (million != 0 && !res.equals(""))
            res += " " + converHelp(million) + " million";
        else if (million != 0 && res.equals(""))
            res += converHelp(million) + " million";
        if (thousand != 0 && !res.equals(""))
            res += " " + converHelp(thousand) + " thousand";
        else if (thousand != 0 && res.equals(""))
            res += converHelp(thousand) + " thousand";
        if (num != 0 && !res.equals(""))
            res += " " + converHelp(num);
        else if (num != 0 && res.equals(""))
            res += converHelp(num);
        return res;
    }

    public static String converHelp(long num)
    {
        String res = "";
        long hundred = num / 100;
        long ten = (num % 100) / 10;
        long unit = num % 10;
        if (ten == 0 && unit != 0)
            res += arr1[(int)unit];
        else if (ten != 0 && unit == 0)
            res += arr3[(int)(ten - 1)];
        else if (ten != 0 && unit != 0)
        {
            if (ten == 1)
                res += arr2[(int)(unit - 1)];
            else
                res += arr3[(int)(ten - 1)] + " " + arr1[(int)unit];
        }
        if (hundred != 0)
            res = arr1[(int)hundred] + " hundred and " + res;
        return res;
    }

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值