題目
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"
Hint:
- Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
- Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
- There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
解題思路
将數從低到高分成三位一組,然後一組一組地處理。注意以下幾點: 1.每組後面可能會有機關 2.在合适的地方加入空格
代碼
public class Solution {
public String numberToWords(int num)
{
String[] weight={""," Thousand"," Million"," Billion"};
String[] table={"Zero","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"};
StringBuffer sb=new StringBuffer();
if(num==0) //num=0
return table[0];
for(int i=0;num!=0;num/=1000,++i)
{
int n=num%1000;
int tmp;
if(n!=0) //weight
sb.insert(0,weight[i]);
tmp=n%100; //the last two digits
if(tmp>0 && tmp<20)
sb.insert(0,table[tmp]);
else if(tmp>=20)
{
if(tmp%10!=0)
sb.insert(0," "+table[tmp%10]);
sb.insert(0,tens[tmp/10-2]);
}
tmp=n/100; //the first digit
if(tmp!=0)
{
if(n%100!=0)
sb.insert(0," ");
sb.insert(0,table[tmp]+" Hundred");
}
if(n!=0 && num/1000!=0)
sb.insert(0," ");
}
return sb.toString();
}
}