题目描述:
Convert a non-negative integer num to its English words representation.
中文描述:
将非负整数 num 转换为其对应的英文表示。
Example 1:
Input: num = 123
Output: “One Hundred Twenty Three”
Example 2:
Input: num = 12345
Output: “Twelve Thousand Three Hundred Forty Five”
Example 3:
Input: num = 1234567
Output: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
Example 4:
Input: num = 1234567891
Output: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”
Constraints:
0 <= num <= 231 - 1
Time complexity:
O
O
O(
N
N
N)
分治法:
根据英语表示位数的有 Hundred 百,Thousand 千, Million 百万,Billion十亿。我们可以用分治法将数字拆封成不同的位数然后递归处理。
例如:1234567890 对用的英语 位数表示 1 Billion 234 Million 567 Thousand 890。
在每个最听的位数表示中 每个数做多是三位数。
总结所有情况:
- =0返回"";
- (0, 20] 用数组存储1~0的英文单词,返回该数字的英文
- (20, 100] 用数组存储 20 ~ 90 整十的英文,返回十位的英文+个位的英文
- (100, 1000] 百位数,返回百位以上数字(递归)(当前数/100)+百位单位+百位以下的数(递归)(当前数%100)
- (1000, 106] 千位数,返回千位以上数字(递归)(当前数/1000)+千位单位+千位以下的数(递归)(当前数%1000)
- (106, 109] 百万位数,返回百万位以上数字(递归)(当前数/106)+百万位单位+百万位以下的数(递归)(当前数%106)
- (109,231 - 1] 十亿位数,返回十亿位以上数字(递归)(当前数/109)+十亿位单位+十亿位以下的数(递归)(当前数%109)
class Solution {
private final String[] Less20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public String numberToWords(int num) {
if (num == 0) return "Zero";
String res = helper(num);
return res.trim();
}
private String helper(int num) {
StringBuilder sb = new StringBuilder();
if (num < 20) {
sb.append(Less20[num]);
} else if (num < 100) {
sb.append(TENS[(num/10)]).append(" ").append(Less20[num % 10]);
} else if (num < 1000) {
sb.append(helper(num / 100)).append(" Hundred ").append(helper(num % 100));
} else if (num < 1000000) {
sb.append(helper(num / 1000)).append(" Thousand ").append(helper(num % 1000));
} else if (num < 1000000000) {
sb.append(helper(num / 1000000)).append(" Million ").append(helper(num %1000000));
} else {
sb.append(helper(num / 1000000000)).append(" Billion ").append(helper(num %1000000000));
}
return sb.toString().trim();
}
}