Skip to content

Commit 66ad69b

Browse files
committed
273
1 parent a2cf9b8 commit 66ad69b

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,5 @@
228228
* [263. Ugly Number](leetcode-263-Ugly-Number.md)
229229
* [264. Ugly Number II](leetcode-264-Ugly-NumberII.md)
230230
* [268. Missing Number](leetcode-268-Missing-Number.md)
231+
* [273. Integer to English Words](leetcode-273-Intege-to-English-Words.md)
231232
* [更多](more.md)
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# 题目描述(困难难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/273.png)
4+
5+
将数字用英文单词表示。
6+
7+
# 思路分析
8+
9+
没有什么特殊的方法,分析规律就可以了,主要有几个点。
10+
11+
* 每三位一组
12+
* 小于 `20` 的和大于 `20` 的分开考虑
13+
* 单词之间空格的处理
14+
* 每三位后边增加个单位,从右数除了第一组,以后每一组后边依次加单位, `Thousand", "Million", "Billion"`
15+
* 我们从右到左遍历,是在倒着完善结果
16+
17+
# 解法一
18+
19+
空格的处理,在每个单词前加空格,最后返回结果的时候调用 `trim` 函数去掉头尾的空格。
20+
21+
倒着遍历的处理,利用 `insert` 函数,每次在 `0` 的位置插入单词。
22+
23+
下边的代码供参考,每个人的代码写出来应该都不同。
24+
25+
```java
26+
public String numberToWords(int num) {
27+
if (num == 0) {
28+
return "Zero";
29+
}
30+
//个位和十位
31+
String[] nums1 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
32+
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
33+
34+
//十位
35+
String[] nums2 = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
36+
37+
//单位
38+
String[] nums3 = { "", "Thousand", "Million", "Billion" };
39+
StringBuilder result = new StringBuilder();
40+
int count = 0; // 记录第几组,方便加单位
41+
while (num > 0) {
42+
int threeNum = num % 1000;
43+
//当前组大于 0 才加单位
44+
if (threeNum > 0) {
45+
result.insert(0, " " + nums3[count]);
46+
}
47+
count++;
48+
int twoNum = num % 100;
49+
if (twoNum < 20) {
50+
//小于 20 两位同时考虑
51+
if (twoNum > 0) {
52+
result.insert(0, " " + nums1[twoNum]);
53+
}
54+
} else {
55+
//个位
56+
if (twoNum % 10 > 0) {
57+
result.insert(0, " " + nums1[twoNum % 10]);
58+
}
59+
//十位
60+
result.insert(0, " " + nums2[twoNum / 10]);
61+
}
62+
//百位
63+
if (threeNum >= 100) {
64+
result.insert(0, " Hundred");
65+
result.insert(0, " " + nums1[threeNum / 100]);
66+
}
67+
num /= 1000;
68+
}
69+
return result.toString().trim();
70+
}
71+
```
72+
73+
#
74+
75+
主要就是对问题的梳理,不是很难。

0 commit comments

Comments
 (0)