我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/integer-to-english-words/
题目描述:
知识点:数学
思路:分区间递归求解
(1)首先,按千来划分,[0, 999],[1000, 999999],[1000000, 999999999],[1000000000, 2 ^ 31 - 1]。
(2)其次,对小于1000的数求得其英文表示,求解过程利用了递归的思想。
时间复杂度和具体数字有关,不好分析。空间复杂度是O(1)。
JAVA代码:
public class Solution {
private static final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"};
private static final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety"};
private static final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (0 == num) {
return "Zero";
}
int i = 0;
String result = "";
while (0 < num) {
if (0 != num % 1000) {
result = helper(num % 1000) + THOUSANDS[i] + " " + result;
}
num /= 1000;
i++;
}
return result.trim();
}
private String helper(int num) {
if (0 == num) {
return "";
} else if (20 > num) {
return LESS_THAN_20[num] + " ";
} else if (100 > num) {
return TENS[num / 10] + " " + helper(num % 10);
} else {
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
}
}
}
LeetCode解题报告: