0%

Leetcode273 Integer to English Words

Leetcode273 Integer to English Words

题目描述

Convert a non-negative integer to its English words representation. Given input is guaranteed to be less than 2的31 - 1.

Example 1:

1
2
Input: 123
Output: "One Hundred Twenty Three"

Example 2:

1
2
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

1
2
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

1
2
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

思路

建立三个数组,第一个string数组保存1-19的English string. 第二个数组保存20,30,40,50,60,70,80,90对应的English String.第三个数组保存hundred,thousand, million,billion,第四个数组中保存100,1000,100* 100, 1000* 1000

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public String numberToWords(int num) {
if(num==0) return "Zero";
return convert(num).substring(0);
}

private static String convert(int num){
String kUnder20[] = {"One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine","Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"};
String kUnder100[] = {"Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"};
String kHTMB[] = {"Hundred", "Thousand", "Million", "Billion"};
int kP[] = {100, 1000, 1000*1000, 1000*1000*1000};
if(num == 0) return "";
if(num<20) {
String result = kUnder20[num-1];
return result;
}
if(num>=20&&num<100){
String result = kUnder100[num/10-2];
if(num%10>0)
result = result +" ";
return result+convert(num%10);

}
for(int i=3;i>=0;i--)
if(num>=kP[i])
return concat(convert(num/kP[i])+" "+ kHTMB[i],convert(num%kP[i]));
return "";
}
private static String concat(String s1, String s2) {
return s1 == "" ? s2 : s2 == "" ? s1 : s1 + " " + s2;
}
}
-------------本文结束感谢您的阅读-------------

Welcome to my other publishing channels