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 }

 

转载于:https://www.cnblogs.com/hwd9654/p/10977427.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值