Leetcode 273.整数转换英文表示

Posted kexinxin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 



以上是关于Leetcode 273.整数转换英文表示的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 273 整数转换英文表示[模拟 字符串] HERODING的LeetCode之路

[LeetCode] 273. Integer to English Words

LeetCode刷题273-困难-整数转换成英文

2022-01-09:整数转换英文表示。将非负整数 num 转换为其对应的英文表示。 示例 1: 输入:num = 123, 输出:“One Hundred Twenty Three“。 力扣273。

273. 整数转换英文表示(模拟&递归)

273 Integer to English Words 整数转换英文表示