将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
示例 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"
本题初看是非常难的感觉,因为变化太多,有billion有million有thousand有hundred,除此之外各个数字的表述都不一样,直观上来说是非常复杂的,那我们需要先抓住这道题的规律,从这个示范的输入中,我们可以发现,每一次都增加了一个新的表述,而这个新的表述是以什么来划分的?
当大于1000 就是thousand
当大于 1000 000 就是million
当大于1000 000 000 就是billion
而如何描述有多少thousand million billion 好像方法是一样的,就是只要看这三位组成的数字是多少即可。那我们就有个想法,就是用一个方法能够从这三位数求出英文表述,再然后加上后缀的thousand,million,billion似乎就可以了。没错方法就是这样的,这样的话我们似乎把题目从转化1-10位数转化为了,如何转化3位数到英文。
我们可以把所有的转化可能都用数组存储起来,然后我们根据位数的不同来决定英文应该是多少,换言之就是暴力的枚举所有可能性,其实需要记录的无非就是0-10,11-19,20,30,...90这几个数字,其他所有的数字都是由这都些数字来组成的。我们可以分为三类来储存。
那想明白了这些,代码也是很好写的,但是要注意的就是 一定要注意 哪里有空格,哪里没空格,哪里的空格是多的,哪里的空格少了,这些情况,我提交了好多次都是因为空格原因失败了。
代码如下:
class Solution {
String[] OneToTen = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
String[] TenToTwenty = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String[] TwentyToHundred = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
public String numberToWords(int num) {
if (num == 0) return "Zero";
int n = num;
String ans = "";
int part1 = n / 1000000000;
if (part1 != 0){
ans = threeNumberToWords(part1) + "Billion ";
}
n %= 1000000000;
int part2 = n / 1000000;
if (part2 != 0){
ans = ans + threeNumberToWords(part2) + "Million ";
}
n %= 1000000;
int part3 = n / 1000;
if (part3 != 0){
ans = ans + threeNumberToWords(part3) + "Thousand ";
}
n %= 1000;
int part4 = n;
ans = ans + threeNumberToWords(part4);
return ans.strip();
}
String threeNumberToWords(int num){
String res = "";
int n = num;
if (n / 100 > 0){
res += OneToTen[(num / 100)] + " Hundred ";
}
n = n % 100;
if (n >= 10 && n < 20){
res += TenToTwenty[n % 10]+" ";
return res;
}
else if (n >= 20){
res += TwentyToHundred[n / 10]+" ";
n %= 10;
}
if( n == 0) return res;
res += OneToTen[n]+" ";
return res;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-to-english-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
网友评论