LeetCode Integer to English Words

时间:2021-02-13 09:20:45

原题链接在这里:https://leetcode.com/problems/integer-to-english-words/

题目:

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

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"

题解:

没三个digit分成一个 unit, 用unitNumber 函数把这三位数换算成数字加上对应的unit.

Note: num = 1,000,000时不可以出现 "One Million Thousand"的情况,所以while循环时 要加上if(rest>0)的限定条件.

Time Complexity: O(n), n是unit的个数 Space: O(1).

AC Java:

 public class Solution {
public String numberToWords(int num) {
if(num == 0){
return "Zero";
}
String res = "";
String [] units = {"", " Thousand", " Million", " Billion"};
int i = 0;
while(num > 0){
int unit = num%1000;
if(unit > 0){ //error 1,000,000
res = unitNumber(unit) + units[i] + (res.length() == 0 ? "" : " "+res);
}
num = num/1000;
i++;
}
return res;
} private String unitNumber(int unit){
String res = "";
String [] ten = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
String [] twenty ={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String [] hundred = {"Zero","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; int a = unit/100;
int b = unit%100;
int c = unit%10; if(a > 0){
res = ten[a] + " Hundred";
} if(b>=10 && b<20){
if(res.length() != 0){
res = res + " ";
}
res = res + twenty[b%10];
return res;
}else if(b >= 20){
if(res.length() != 0){
res = res + " ";
}
b = b/10;
res = res + hundred[b];
} if(c > 0){
if(res.length() != 0){
res = res + " ";
}
res = res + ten[c];
}
return res;
}
}