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"Solution 1: coding skill.
public class Solution {
public String numberToWords(int num) {
String[] ones={"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"};
String[] thousands={"Thousand","Million","Billion"};
int[] nums={1000,1000000,1000000000};
if (num<20) return ones[num];
if (num<100) return tens[num/10]+((num%10==0)?"":" "+ones[num%10]);
if (num<1000) return ones[num/100]+" Hundred"+((num%100==0)?"":" "+numberToWords(num%100));
for (int i=0; i<3; i++) {
if (i==2 || num<nums[i+1]) {
return numberToWords(num/nums[i])+" "+thousands[i]+((num%nums[i]==0)?"":" "+numberToWords(num%nums[i]));
}
}
return "";
}
}
没有评论:
发表评论