lc273 Integer to English Words

這道題竟然是hard..
邏輯很簡單,但是edge case和各種容易犯錯的小細節非常多。

  • thousand/million/billion在0後面不加
  • 空格的問題
  • ten和eleven~nineteen的區分
  • zero在不同chunk
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
class Solution {
vector<string> lessThan20 = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
vector<string> tens = {"", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
vector<string> thousands = {"", "Thousand ","Million ","Billion "};
public:
string convertChunk(int num) {
int n = num;
string s="";
if (num/100) s+= lessThan20[num/100] + "Hundred ";
n%=100;
if (n < 20) s+=lessThan20[n];
else s+=tens[n/10] +lessThan20[n%10];
return s;
}
string numberToWords(int num) {
if (!num) return "Zero";
string s = "";
int cnt = 0;
while (num) {
string tmp = convertChunk(num%1000);
if (tmp != "") s= tmp+thousands[cnt]+s;
else s= tmp+s;
cnt++;
num/=1000;
}
return s.substr(0,s.length()-1);
}
};