273. Integer to English Words


//
看看人家的转换int为String吧,真的很不错啊!主要是在1000以内的数自由转换的时候我没做好 private static final String[] lessThan20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private static final String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; private static final String[] thousands = { "", "Thousand", "Million", "Billion" }; /* * 273. Integer to English Words * 1.14 by Mingyang * 这个题目自己动手做的时候一团mess,所以我们看看这个网上比较精炼的代码 * 这个题目其实很简单,从最低为开始,每三位得出一个读书,加上计量单位,依次往后 * 那么重点在于三位数怎么读,怎么分类: * 1.小于20,自然直接读出来了 * 2.小于100,需要加几十的读音,加剩下的数(不能再用小于20数组,因为空格不对) * 3.大于100的先加hundred。再来数字余下的 */ public static String numberToWords(int num) { if (num == 0) { return "Zero"; } String result = ""; int i = 0; while (num > 0) { if (num % 1000 != 0) { result = helper(num % 1000) + thousands[i] + " " + result; } num /= 1000; i++; } return result.trim(); } private static String helper(int num) { if (num == 0) { return ""; } else if (num < 20) { return lessThan20[num] + " "; } else if (num < 100) {
//这里我们把helper改为lessThan20,因为我们这里有个空格fifty thousand只有一个空格, //而lessThan20[num] + " "(多一个空格) return tens[num / 10] + " " + helper(num % 10); } else { return lessThan20[num / 100] + " Hundred " + helper(num % 100); } }
原文地址:https://www.cnblogs.com/zmyvszk/p/5619034.html