Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
Hint:
- Group the digits by thousand using mod operator
- Use a helper function to convert the chunk to words
Edge case:
- Input is zero
class Solution {
public String numberToWords(int num) {
if (num == 0) return "Zero";
String[] ones = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"};
String[] tens = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred"};
String[] thousands = {" ", "Thousand", "Million", "Billion"};
String ret = "";
int i = 0;
while (num > 0) {
if (num % 1000 != 0) {
ret = format(num % 1000, ones, tens) + thousands[i] + " " + ret;
}
num = num / 1000;
i ++;
}
return ret.trim();
}
private String format(int num, String[] ones, String[] tens) {
StringBuilder sb = new StringBuilder();
if (num >= 100) {
sb.append(ones[num / 100 - 1]).append(" ").append("Hundred ");
num = num % 100;
}
if (num > 20) {
sb.append(tens[num / 10 - 2]).append(" ");
num = num % 10;
}
if (num > 0) {
sb.append(ones[num - 1]).append(" ");
}
return sb.toString();
}
}
网友评论