首页 > 编程语言 >#yyds干货盘点# LeetCode程序员面试金典:整数的英语表示

#yyds干货盘点# LeetCode程序员面试金典:整数的英语表示

时间:2023-02-25 21:32:01浏览次数:48  
标签:yyds curr String 金典 num StringBuffer Hundred LeetCode append

题目:

给定一个整数,打印该整数的英文描述。

示例 1:

输入: 123

输出: "One Hundred Twenty Three"

示例 2:

输入: 12345

输出: "Twelve Thousand Three Hundred Forty Five"

示例 3:

输入: 1234567

输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

示例 4:

输入: 1234567891

输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

代码实现:

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

public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
StringBuffer sb = new StringBuffer();
for (int i = 3, unit = 1000000000; i >= 0; i--, unit /= 1000) {
int curNum = num / unit;
if (curNum != 0) {
num -= curNum * unit;
StringBuffer curr = new StringBuffer();
recursion(curr, curNum);
curr.append(thousands[i]).append(" ");
sb.append(curr);
}
}
return sb.toString().trim();
}

public void recursion(StringBuffer curr, int num) {
if (num == 0) {
return;
} else if (num < 10) {
curr.append(singles[num]).append(" ");
} else if (num < 20) {
curr.append(teens[num - 10]).append(" ");
} else if (num < 100) {
curr.append(tens[num / 10]).append(" ");
recursion(curr, num % 10);
} else {
curr.append(singles[num / 100]).append(" Hundred ");
recursion(curr, num % 100);
}
}
}


标签:yyds,curr,String,金典,num,StringBuffer,Hundred,LeetCode,append
From: https://blog.51cto.com/u_13321676/6085690

相关文章