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

相关推荐
weixin_45544617几秒前
Python学习的主要知识框架
开发语言·python·学习
蜗牛^^O^31 分钟前
Docker和K8S
java·docker·kubernetes
从心归零1 小时前
sshj使用代理连接服务器
java·服务器·sshj
IT毕设梦工厂2 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius3 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
LvManBa3 小时前
Vue学习记录之六(组件实战及BEM框架了解)
vue.js·学习·rust
七夜zippoe3 小时前
分布式系统实战经验
java·分布式
LvManBa3 小时前
Vue学习记录之三(ref全家桶)
javascript·vue.js·学习
是梦终空3 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票