Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
public class Solution {
private final String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private final String[] lessThan20 = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private final String[] thousands = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
String res = "";
int sig = 0;
while (num != 0) {
StringBuilder sb = new StringBuilder();
int val = num % 1000;
if (val != 0) {
int hundred = val / 100;
if (hundred != 0) {
sb.append(ones[hundred]).append(" ").append("Hundred").append(" ");
}
val = val % 100;
if (val >= 10 && val < 20) {
sb.append(lessThan20[val - 10]).append(" ");
} else if (val > 0 && val < 10) {
sb.append(ones[val]).append(" ");
} else if (val >= 20) {
int ten = val / 10;
sb.append(tens[ten]).append(" ");
int digit = val % 10;
if (digit != 0) {
sb.append(ones[digit]).append(" ");
}
}
}
if (sb.length() != 0) {
sb.append(thousands[sig]);
res = sb.toString().trim() + " " + res;
}
sig++;
num /= 1000;
}
return res.trim();
}
}
============
public class Solution {
private final String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private final String[] lessThan20 = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private final String[] thousands = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
String res = "";
int sig = 0;
while (num != 0) {
int val = num % 1000;
if (val != 0) {
StringBuilder sb = new StringBuilder();
int hundred = val / 100;
if (hundred != 0) {
sb.append(ones[hundred]).append(" ").append("Hundred").append(" ");
}
val = val % 100;
if (val >= 10 && val < 20) {
sb.append(lessThan20[val - 10]).append(" ");
} else if (val > 0 && val < 10) {
sb.append(ones[val]).append(" ");
} else if (val >= 20) {
int ten = val / 10;
sb.append(tens[ten]).append(" ");
int digit = val % 10;
if (digit != 0) {
sb.append(ones[digit]).append(" ");
}
}
sb.append(thousands[sig]).append(" ");
res = sb.toString() + res;
}
sig++;
num /= 1000;
}
return res.trim();
}
}
没有评论:
发表评论