[leetcode] Integer to English Words
2015-11-27 13:39
260 查看
题目:
分析:英语中只有十(ten),百(hundred),千(thousand),百万(million),十亿(billion),万亿(trillion),因为输入的数最大为2^31 - 1,故这里用不着万亿(trillion),其中1 trillion = 1000 billion = 10^6 million = 10^9 thousand = 10^12. 另外注意英语数字中小于20的单词都是不唯一不能组合的。
思路:从数字的低位开始,结合辅助数组,每三位(1000)处理一次,代码如下:
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); } } }
相关文章推荐
- 数据结构系列——Java后缀树实现代码
- mysql修改表、字段、库的字符集
- MySQL学习1-软件下载
- java生成二维码
- 1019. General Palindromic Number (20)
- AndroidManifest.xml文件配置整理集合
- shell脚本里获取字符串的最后一个字符
- 话题13 --鞭辟入里 条件表达式的类型深入
- 黑客攻击的入口--端口
- sumline text 正则匹配
- Android RecyclerView的使用
- Android二维码讲解(ZXing)
- respondsToSelector的相关使用
- 重新安装.net framework 4.5
- Jquery根据元素值或元素下标来删除一个数组元素及数组对象方法
- WCF 服务器调用回调函数 单程-双程操作模式:
- UE4 编译后 不能正常使用Open Level 打开关卡解决方案:Open Level Blueprint Node not workin
- javascript设计模式实践之策略模式--输入验证
- 数据结构系列——后缀树(附Java实现代码)
- 点击客服qq后关闭打开的空白页