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"

题目:

给定一个整数,像check一样将该数字用英文读出来

思路:

1. Coz given input is less than 2 - 1, we can say that the highest digit level is billion

2. We divide input into N parts, all the parts follow the similar partten of converting.  We use helper function to help recursive call.

代码:

 class Solution {
// coz array index begins at 0, so we use "" to empty a space
private final String[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private final String[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; public String numberToWords(int num) {
if (num == 0) return "Zero";
return helper(num);
} private String helper(int num) {
String result = new String();
if (num < 10) result = belowTen[num];
else if (num < 20) result = belowTwenty[num -10];
// if num is smaller than 100, keep tens digit and add units digit
else if (num < 100) result = belowHundred[num/10] + " " + helper(num % 10);
// if num is smaller than thousand, call helper to get how many hundreds, call the helper to get the rest digits
else if (num < 1000) result = helper(num/100) + " Hundred " + helper(num % 100);
// if num is smaller than million, call helper to get how many thousands, call the helper to get the rest digits
else if (num < 1000000) result = helper(num/1000) + " Thousand " + helper(num % 1000);
// if num is smaller than billion, call helper to get how many millions, call the helper to get the rest digits
else if (num < 1000000000) result = helper(num/1000000) + " Million " + helper(num % 1000000);
else result = helper(num/1000000000) + " Billion " + helper(num % 1000000000);
return result.trim();
}
}
05-11 16:09
查看更多