JAVA学习-练习试用Java实现“整数转换英文表示”

问题:

将非负整数 num 转换为其对应的英文表示。示例 1:

输入:num = 123
输出:"One Hundred Twenty Three"
示例 2:

输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"
示例 3:

输入:num = 1234567
输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:

输入:num = 1234567891
输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
提示:0 <= num <= 231 - 1

解答思路:

以下是使用 Java 语言实现将非负整数转换为英文表示的代码:

public class IntegerToEnglishWords {
    public static String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }

        String[] belowTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        String[] thousands = {"", "Thousand", "Million", "Billion"};

        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (num > 0) {
            if (num % 1000!= 0) {
                sb.insert(0, thousands[i] + " ");
                int hundred = num / 100;
                num %= 100;
                if (hundred > 0) {
                    sb.insert(0, belowTwenty[hundred] + " Hundred ");
                }
                if (num > 0 && num < 20) {
                    sb.insert(0, belowTwenty[num] + " ");
                } else if (num >= 20) {
                    sb.insert(0, tens[num / 10] + " ");
                    num %= 10;
                    if (num > 0) {
                        sb.insert(0, belowTwenty[num] + " ");
                    }
                }
            }
            num /= 1000;
            i++;
        }

        return sb.toString().trim();
    }

    public static void main(String[] args) {
        int num = 1234567891;
        System.out.println(numberToWords(num));
    }
}

这个程序首先定义了一些数组,用于表示数字的英文单词。然后,它使用一个循环来处理数字的每三位,并将其转换为英文单词。在循环中,它根据数字的大小选择合适的单词,并将其添加到结果字符串中。最后,它返回结果字符串。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值