首页 > 代码库 > LeetCode-Integer to English Words
LeetCode-Integer to English Words
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:
BE CAREFUL: all kinds of corner cases
public class Solution { String[] suffixs = new String[]{"","Thousand", "Million","Billion"}; String[] tens = new String[]{"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty", "Ninety"}; String[] tenTwenty = new String[]{"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; String[] singles = new String[]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; public String numberToWords(int num) { if (num==0) return "Zero"; StringBuilder builder = new StringBuilder(); int base = 1000; int index = 0; while (num!=0){ int sectionNum = num%base; num = num / base; addSection(builder,sectionNum,suffixs[index++]); } return builder.toString().trim(); } public void addSection(StringBuilder builder, int sectionNum, String suffix){ if (sectionNum==0){ return; } builder.insert(0," "+suffix); int hundreds = sectionNum / 100; int left = sectionNum % 100; if (left > 0){ if (left<10){ builder.insert(0,singles[left]).insert(0," "); } else if (left>=10 && left < 20){ builder.insert(0,tenTwenty[left-10]).insert(0," "); } else { String temp = " " + tens[left/10] + ((left%10==0) ? "" : (" " + singles[left%10])); builder.insert(0,temp); } } if (hundreds>0){ String temp = " " + singles[hundreds] + " Hundred"; builder.insert(0,temp); } }}
LeetCode-Integer to English Words
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。