LC.273 Integer to English Words

本文最后更新于:2024年2月29日 上午

前言

外国数字的读法和国内不同,其分割方式为

2,234,911,679
即每三个数为一组,从后向前分别视作

679

911个千

234个万

2个亿

递归模拟

思路分析


有了以上对数字的分析,我们就会发现,把数字转变为英文写法,无非就是分组后的数字读法 + 数量级(千,万)

对于数字数量级分组,可以采用除法 + 整除的形式;

在数字读法方面,还需要有更细致的讨论:

  • 众所周知,英文中100一下的数字分为三个部分
    • [0 - 10)
    • [10 - 20]
    • (20 - 99]
  • 对于[0 - 10)或[10 - 20]内的数字,可以直接返回读法
  • 对于(20, 99]的数字读法为(这里用45举例):
    • “Forty Five”
    • 40的读法 + 5的读法
  • 基于此,我们事先打表一套英文数字读法表,按需求往ans中添加即可

细节方面,需要注意空格问题;参考代码中,数量级后加空格而前不加空格,计算数字读法时对每一位后都加空格;由此最后还需要弹出位于末尾的无用空格

参考代码


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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
private:
vector<string> singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
vector<string> ten2Twenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen"};
vector<string> tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

public:
string underHundred(int n) {
string ans;
int hundred = n / 100;
if (hundred) {
ans += singles[hundred] + " Hundred ";
}
n %= 100;
if (n < 20 && n >= 10) {
ans += ten2Twenty[n % 10] + " ";
return ans;
}
if (n >= 20) {
ans += tens[n / 10] + " ";
}
n %= 10;
if (n == 0) return ans;
ans += singles[n % 10] + " ";
return ans;
}

string recur(int n) {
string ans;

int billion = n / 1000000000;
n %= 1000000000;
int million = n / 1000000;
n %= 1000000;
int thousand = n / 1000;
n %= 1000;

if (billion) {
ans += recur(billion) + "Billion ";
}
if (million) {
ans += recur(million) + "Million ";
}
if (thousand) {
ans += recur(thousand) + "Thousand ";
}

ans += underHundred(n);
return ans;
}

string numberToWords(int num) {
if (num == 0) return "Zero";
string ans = recur(num);
ans.pop_back();
return ans;
}
};

文章参考


【微扰理论】模拟题 英文数字三位一组 (微软面试题原题)


LC.273 Integer to English Words
http://example.com/2022/06/30/LC273-Integer-to-English-Words/
作者
Haruko
发布于
2022年6月30日
更新于
2024年2月29日
许可协议