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