Leetcode 273.整数转换英文表示

整数转换英文表示

将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1

示例 1:

输入: 123

输出: "One Hundred Twenty Three"

示例 2:

输入: 12345

输出: "Twelve Thousand Three Hundred Forty Five"

示例 3:

输入: 1234567

输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

示例 4:

输入: 1234567891

输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

 1 class Solution {
 2     static String num1[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
 3     static String num2[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
 4     static String tens[]={"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
 5     public String numberToWords(int num) {
 6         if(num==0){
 7             return "Zero";
 8         }
 9         String result="";
10         if(num>999999999){
11             result+=numberToWordsWithThreeDIgit(num/1000000000)+" Billion";
12             num%=1000000000;
13         }
14         if(num>999999){
15             result+=numberToWordsWithThreeDIgit(num/1000000)+" Million";
16             num%=1000000;
17         }
18         if(num>999){
19             result+=numberToWordsWithThreeDIgit(num/1000)+" Thousand";
20             num%=1000;
21         }
22         if(num>0){
23             result+=numberToWordsWithThreeDIgit(num);
24         }
25         return result.trim();
26     }
27 
28     public String numberToWordsWithThreeDIgit(int num){
29         String result="";
30         if(num>99){
31             result+=" "+num1[num/100-1]+" Hundred";
32         }
33         num%=100;
34         if(num>19){
35             result+=" "+tens[num/10-2];
36             num%=10;
37         }else if(num>9){
38             result+=" "+num2[num-10];
39             num=0;
40         }
41         if(num>0){
42             result+=" "+num1[num-1];
43         }
44         return result;
45     }
46 }


原文地址:https://www.cnblogs.com/kexinxin/p/10204954.html