273. Integer to English Words
Hard
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"
Solution:
three digits one group, parse 3 digits.
public String numberToWords(int num) {
if(num == 0) return "Zero";
StringBuilder sb = new StringBuilder();
int threeDigits = num %1000;
sb.insert(0,parse3digits(threeDigits));
String[] thousands = {"Thousand","Million","Billion"};
int index = 0;
while(num > 0){
num = num/1000;
threeDigits = num %1000;
if(threeDigits > 0){
sb.insert(0,parse3digits(threeDigits) +" "+ thousands[index]+" ");
}
index++;
}
String res = sb.toString().trim();
return res;
}
public String parse3digits(int num){
String[] to19 = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String[] tens = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"
};
int firstDigit = num/100;
StringBuilder sb = new StringBuilder();
if(firstDigit > 0){
sb.append(to19[firstDigit] + " Hundred ");
}
int lastTwoDigits = num%100;
if(lastTwoDigits >= 20){
int secondDigit = lastTwoDigits/10;
sb.append(tens[secondDigit] + " ");
int lastDigit = num%10;
sb.append(to19[lastDigit]);
}else{
sb.append(to19[lastTwoDigits]);
}
return sb.toString().trim();
}
Solution2:
The given number is divided in two parts: the part divide
class Solution {
public String numberToWords(int num) {
if(num == 0) return "Zero";
String res = in2String(num);
return res.trim();
}
public String in2String(int num){
String[] tens = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
String res = "";
if(num>=1000000000){
res = in2String(num/1000000000) + " Billion " + in2String(num%1000000000);
}else if(num >= 1000000){
res = in2String(num/1000000) + " Million " + in2String(num%1000000);
}else if(num >= 1000){
res = in2String(num/1000) + " Thousand " + in2String(num%1000);
}else if(num >= 100){
res = in2String(num/100) + " Hundred " + in2String(num%100);
}else if(num >= 20){
int secondDigit = num/10;
res = tens[secondDigit] + " " + in2String(num%10);
}else if(num > 0){
String[] to19 = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
res = " "+ to19[num];
}
return res.trim();
}
}
Comments
Post a Comment