题目:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 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"
分析:英语中只有十(ten),百(hundred),千(thousand),百万(million),十亿(billion),万亿(trillion),因为输入的数最大为2^31 - 1,故这里用不着万亿(trillion),其中1 trillion = 1000 billion = 10^6 million = 10^9 thousand = 10^12. 另外注意英语数字中小于20的单词都是不唯一不能组合的。
思路:从数字的低位开始,结合辅助数组,每三位(1000)处理一次,代码如下:
public class Solution { String[] lessThan20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String hundred = "Hundred"; String[] thousands = {"", "Thousand", "Million", "Billion"}; public 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 String helper(int i) { if (i == 0) { return ""; } else if (i < 20) { return lessThan20[i] + " "; } else if (i < 100) { return tens[i/10] + " " + helper(i%10); } else { return helper(i/100) + hundred + " " + helper(i%100); } } }
时间: 2024-11-06 02:31:00