A C++ solution used map

• ``````string numberToWords(int n)
{
if (0 == n)
return "Zero";
string ret;
map<int, string> num =
{
{ 0, "" }, //except '0', there is a space in the last of string.
{ 1, "One " },
{ 2, "Two " },
{ 3, "Three " },
{ 4, "Four " },
{ 5, "Five " },
{ 6, "Six " },
{ 7, "Seven " },
{ 8, "Eight " },
{ 9, "Nine " },
{ 10, "Ten " },
{ 11, "Eleven " },
{ 12, "Twelve " },
{ 13, "Thirteen " },
{ 14, "Fourteen " },
{ 15, "Fifteen " },
{ 16, "Sixteen " },
{ 17, "Seventeen " },
{ 18, "Eighteen " },
{ 19, "Nineteen " }
}; //Use map to pair the number less than 20.
vector<string> v1 = { "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ",
"Eighty ", "Ninety " };
vector<string> v2 = { "", "Thousand ", "Million ",  "Billion " };
int t, cout = 0; //count the number of ','
for (; n && cout < 4; n /= 1000, ++cout)
{
t = n % 1000;
if (0 == t)
continue;
ret = v2[cout] + ret;
if ((t % 100) < 20)
ret = num[t % 100] + ret;
else
ret = v1[(t / 10) % 10] + num[t % 10] + ret;
if (t / 100)
ret = num[(t / 100) % 10] + "Hundred " + ret;
}
ret.erase(ret.end() - 1); //erase string's last space.
return ret;
}
``````

I have convert the number from right to left. It might be faster if converted from left to right.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.