leetcode 273 Integer to English Words

Posted hwd9654

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 273 Integer to English Words相关的知识,希望对你有一定的参考价值。

lc273 Integer to English Words

分析英文的计数规则,1000一个循环,thousand,million,billion,trillion,所以我们可以每1000处理一次,后面加上相应的thousand或是million…

然后再看1000以内规则:

hundred一档,ten一档,0~9一档

不过要注意11,12,13~19是特殊的,

所以我们可以先处理>=100的部分,然后是>=20的部分,最后是剩下的<20部分

 1 class Solution 
 2         private final String[] less20 = "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen";
 3         private final String[] less100 = "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety";
 4         private final String[] thousands = "", "Thousand", "Million", "Billion";
 5         
 6     public String numberToWords(int num) 
 7         if(num == 0)
 8             return "Zero";
 9         String res = "";
10         int i=0;
11         
12         while(num > 0)
13             if(num % 1000 != 0)
14                 res = helper(num % 1000) + thousands[i] + " " + res;
15             
16             i++;
17             num /= 1000;
18         
19         return res.trim();
20     
21     
22     private String helper(int num)
23         if(num == 0)
24             return "";
25         else if(num < 20)
26             return less20[num] + " ";
27         else if(num < 100)
28             return less100[num / 10] + " " + helper(num % 10);
29         else
30             return less20[num / 100] + " Hundred " + helper(num % 100);
31     
32 

 

以上是关于leetcode 273 Integer to English Words的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 273: integer to English Words

leetcode 273 Integer to English Words

[LeetCode] 273. Integer to English Words

[LeetCode] 273. Integer to English Words 整数转为英文单词

[leetcode]273. Integer to English Words 整数转英文单词

LeetCode 273. Integer to English Words