原题链接 https://leetcode.com/problems/integer-to-english-words/
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
每3位做一次处理
class Solution {
public:
string numberToWords(int num) {
if (num == 0)return Oto19[0];
string res = "";
int pos = 9;
bool flag = false;
int tmp = num % 1000;
num /= 1000;
per3ToWord(tmp);
while (num)
{
tmp = num % 1000;
num /= 1000;
if (tmp)
ans.push_front(zoTo[pos]);
pos++;
per3ToWord(tmp);
}
for (auto& item : ans)
{
if (!flag)flag = true;
else res += " ";
res += item;
}
return res;
}
void per3ToWord(int num)
{
int a = num / 100;
num %= 100;
int b = num / 10;
num %= 10;
int c = num;
if (b > 1)
{
if (c)
ans.push_front(Oto19[c]);
ans.push_front(zoTo[b - 2]);
}
else if (b != 0 || c != 0)
{
ans.push_front(Oto19[b*10 + c]);
}
if (a)
{
ans.push_front("Hundred");
ans.push_front(Oto19[a]);
}
return;
}
private:
static string Oto19[20];
static string zoTo[12];
deque<string> ans;
};
string Solution::Oto19[20] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
string Solution::zoTo[12] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred", "Thousand", "Million", "Billion" };