Title description
AC code
The meaning of this question is to give you a number so that you can express the corresponding English reading. Reading a number in English has a characteristic that every three numbers are a group (you can observe the sample reading given). That we can represent a number: the range wherein the array is underlined 1 to 999 (the last underline, this number 0 Laid separate out sentence), __million__billion__thousand___
. You can write a part function separately for each underlined part, that is to say, enter a number within 1000, the part method can return its corresponding English reading, and finally each part is spliced on the corresponding million / billion / thousand .
class Solution {
String[] small={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String[] decade={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
String[] big={"Billion","Million","Thousand",""};
public String numberToWords(int num) {
//特判0。
if(num==0) return small[0];
String res="";
for(int i=1000000000,j=0;i>0;i/=1000,j++)
{
if(num>=i){
res+=part(num/i)+big[j]+' ';
num%=i;
}
}
while(res.charAt(res.length()-1)==' ') res=res.substring(0,res.length()-1);
return res;
}
String part(int num){
String res="";
if(num>=100){
//此处需要注意Hundred前后都有空格
res+=small[num/100]+" Hundred ";
num%=100;
}
if(num==0) return res;
//小于20的,可以直接加
if(num>=20){
res+=decade[num/10]+' ';
num%=10;
}
if(num==0) return res;
res+=small[num]+' ';
return res;
}
}