273. Integer to English Words
Posted hutong749
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了273. Integer to English Words相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/integer-to-english-words/description/
要求把一个数字转换成英语。
1,000,000,000,000
想到没三位可以成一组,每组内的形成方式是一样的。只是最后加的千位符号不一样 -- "","Thousand", "Million", "Billion", "Trillion"
所以我们可以把三位为一组。先实现三位数的表示方法。再递归调用这个方法。
这个题的时间复杂度基本是O(N) recursion 的深度也不回太深。
对于Integer 最大值: 2^31-1 = 2,147,483,647 about 2 billion
一个估算方法
2^10 is very near to 1000,
so 2^(3*10) is 1000^3 or about 1 billion.
One of the 32 bits is used for sign, so the max value is really only 2^31
which is about twice the amount you get for 2^(3*10): = 2 billion
String[] belowTwenty = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String[] beyond = new String[]{"","Thousand", "Million","Billion", "Trillion"}; public String numberToWords(int num) { if(num == 0){ return "Zero"; } return helper(num, 0).trim(); //主程序中递归调用三位数 }
private String helper(int num, int count){ if(num == 0) return ""; String higher = helper(num/1000, count +1); String ans = convertToNNN(num%1000); if(ans.length() > 0) { return higher + " " + ans + " " + beyond[count] ; } return higher; } //形成三位数 private String convertToNNN(int num){ if(num < 100){ return convertToNN(num); } if(num % 100 == 0){ return belowTwenty[num/100] + " Hundred"; } return belowTwenty[num/100] + " Hundred " + convertToNN(num % 100); }
//形成两位数 private String convertToNN(int num){ if(num < 20){ return belowTwenty[num]; } if(num % 10 == 0){ return belowHundred[num/10]; } return belowHundred[num/10] + " " + belowTwenty[num%10]; }
以上是关于273. Integer to English Words的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 273. Integer to English Words
[LC] 273. Integer to English Words