Leetcode: Integer to English Words
2015-12-26 00:08
417 查看
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"
Career Cup 150 Pg 442
Think of Convert(19,323,984) = Process(19) + "million" + Process(323) + "thousand" + Process(984) + ""
The Process is a process that generates words representation for integer below 1000
public class Solution { String[] digits = new String[]{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; String[] teen = new String[]{"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String[] tens = new String[]{"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String[] bigs = new String[]{"", "Thousand", "Million", "Billion"}; public String numberToWords(int num) { String res = new String(); if (num == 0) return "Zero"; int count = 0; while (num > 0) { int belowThousand = num % 1000; if (belowThousand != 0) { res = process(belowThousand) + " " + bigs[count] + " " + res; } count++; num = num / 1000; } return res.trim(); } public String process(int n) { String res = new String(); if (n/100 > 0) { res = digits[n/100-1] + " " + "Hundred" + " "; n = n%100; } if (n>=11 && n<=19) { res = res + teen[n%10-1]; return res; } else if (n/10 > 0) { res = res + tens[n/10-1] + " "; n = n%10; } if (n > 0) { res = res + digits[n-1]; } return res.trim(); } }
相关文章推荐
- 笔试题目总结之三——软件工程中的开发模式
- Linux学习之: rpm包管理功能全解
- Leetcode-300.Longest Increasing Subsequence
- do{}while(0);详解
- 【C语言】输出从公元1000年至2000年所有闰年的年号,每输出3个年号换一行!
- 笔试题目总结之二——常用数据结构与算法
- bzoj1934【shoi2007】Vote善意的投票
- 【Android】《第一行代码—Android》第四章总结
- <二>Material主题的使用
- 单例模式
- 解决键盘遮挡输入框问题
- 81、交换机配置实验之NTP
- TCP的交互数据流
- 今年学习的重点
- pureftpd 启用系统帐户登录
- TCP/IP四层协议栈
- SQLServer 维护脚本分享(06)CPU
- 工厂模式(Factory Patter)
- 软件工程学习总结
- 分享50个提高PHP执行效率的技巧