每日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”

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-to-english-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这个题很简单,直接按照三位分开之后分别转换就行,重点在于单词拼写

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
class Solution {
public:
string numberToWords(int num) {
int splited[4] = { 0 };
string numbers[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string tensnumbers[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string biggertennumbers[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
if (num == 0) {
return "Zero";
}
for (int i = 0; i < 4; i++) {
splited[i] = num % 1000;
num = num / 1000;
}
string ans = "";
for (int i = 3; i >= 0; i--) {
int data = splited[i];
if (data > 0) {
if (data / 100) {
ans += numbers[data / 100] + " Hundred ";
}
data = data % 100;
if (data > 0) {
if (data < 10) {
ans += numbers[data] + " ";
}
else if (data >= 20) {
ans += tensnumbers[data / 10] + " ";
data = data % 10;
if (data > 0) {
ans += numbers[data] + " ";
}
}
else {
ans += biggertennumbers[data - 10] + " ";
}
}
if (i == 3) {
ans += "Billion ";
}
else if (i == 2) {
ans += "Million ";
}
else if (i == 1) {
ans += "Thousand ";
}
}
}
return ans.substr(0, ans.size() - 1);
}
};