整数的英语表示
难度:
标签:
题目描述
Given any integer, print an English phrase that describes the integer (e.g., "One Thousand Two Hundred Thirty Four").
Example 1:
Input: 123 Output: "One Hundred Twenty Three"
Example 2:
Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
代码结果
运行时间: 31 ms, 内存: 16.2 MB
/*
思路:
1. 使用与上述Java解法相同的思路,但尽可能地使用Java Stream API来处理数据。
*/
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class NumberToWordsStream {
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 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private static final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (num == 0) return "Zero";
int[] parts = new int[4];
int i = 0;
while (num > 0) {
parts[i++] = num % 1000;
num /= 1000;
}
return IntStream.range(0, 4)
.mapToObj(j -> parts[j] > 0 ? helper(parts[j]) + THOUSANDS[j] : "")
.filter(s -> !s.isEmpty())
.collect(Collectors.joining(" "))
.trim();
}
private String helper(int num) {
if (num == 0)
return "";
else if (num < 20)
return LESS_THAN_20[num] + " ";
else if (num < 100)
return TENS[num / 10] + " " + helper(num % 10);
else
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
}
}
解释
方法:
The solution converts a given integer to its English words representation. It uses a dictionary to map numbers to their English counterparts for single digits, two digits, and multiples of ten. The algorithm handles the integer in chunks of three digits, corresponding to the place values like Thousand, Million, etc. These chunks are processed from right to left, adjusting for place value. Special attention is given to numbers like '100' or '110' where 'Zero' needs to be managed correctly to avoid incorrect outputs like 'Zero Hundred'. The final English representation is then constructed by reversing the order of processed chunks and concatenating them with appropriate place values.
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
如何处理输入的整数中包含的前导零或者整个数是零的情况?
▷🦆
在处理数的每三位的过程中,如果遇到类似于'001'或'010'这样的数字,算法是如何确保不会输出多余的'Zero'或'Zero Hundred'?
▷🦆
算法是怎样处理两位数中间的零,比如'105',确保输出是'One Hundred Five'而不是'One Hundred Zero Five'?
▷