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 语言实现将非负整数转换为英文表示的代码:

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过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)

相关推荐
Aision_1 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
剑飞的编程思维1 小时前
真实学习本质-坚持思考的人
学习
AI浩1 小时前
学习嵌入位置:面向小目标检测查询检索的噪声感知位置编码
人工智能·学习·目标检测
辞旧 lekkk5 小时前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
zc.z5 小时前
JAVA实现:纯PCM格式音频转换成BASE64
java·音视频·pcm
mask哥5 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
Aaswk6 小时前
Java Lambda 表达式与流处理
java·开发语言·python
是宇写的啊7 小时前
Spring AOP
java·spring
万邦科技Lafite7 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
Mr_pyx8 小时前
Spring AI 入门教程:Java开发者的AI应用捷径
java·人工智能·spring