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

相关推荐
im_AMBER2 分钟前
算法笔记 16 二分搜索算法
c++·笔记·学习·算法
摇滚侠2 分钟前
2025最新 SpringCloud 教程,Nacos-总结,笔记19
java·笔记·spring cloud
赵文宇(温玉)6 分钟前
不翻墙,基于Rancher极速启动Kubernetes,配置SSO登录,在线环境开放学习体验
学习·kubernetes·rancher
在逃热干面6 分钟前
(笔记)获取终端输出保存到文件
java·笔记·spring
爱笑的眼睛117 分钟前
深入理解MongoDB PyMongo API:从基础到高级实战
java·人工智能·python·ai
笃行客从不躺平16 分钟前
遇到大SQL怎么处理
java·开发语言·数据库·sql
q***876023 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端
Billow_lamb25 分钟前
Spring Boot2.x.x全局拦截器
java·spring boot·后端
上不如老下不如小35 分钟前
2025年第七届全国高校计算机能力挑战赛初赛 Java组 编程题汇总
java·计算机能力挑战赛
泉城老铁1 小时前
Springboot对接mqtt
java·spring boot·后端