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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
#include <vector>
using namespace std;
const string F20[] = {"", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
const string TENS[] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety"};
const string HUN = "hundred";
const string THOU[] = {"", "thousand", "million", "billion", "trillion"};
string NumToWords(long n)
{
if (n==0) { return "zero"; }
int prev_d = n%10; // Previous digit, esp. for stuff like 'twelve'
stack<string> st;
st.push(F20[prev_d]);
n /= 10;
int d; // Current digit
int i = 1; // Index from the right
while (n)
{
d = n%10;
if ( i%3 == 0 ) // thousands
{
if (d>=1)
{
st.push(THOU[i/3]);
st.push(F20[d]);
}
}
else if ( (i+1)%3 == 0 ) // hundreds
{
if (d>=1)
st.push(F20[d] + " " + HUN);
}
else // tens
{
if (d==1)
{
st.pop();
st.push(F20[10+prev_d]);
}
else if (d>1)
{
st.push(TENS[d] + "-");
}
}
prev_d = d;
n/=10;
i+=1;
}
// Build string, adding space if top doesnt end in a dash
ostringstream oss;
while (!st.empty())
{
string& top = st.top();
oss << top;
if (top.back() != '-')
oss << ' ';
st.pop();
}
return oss.str();
}
int main()
{
vector<long> numbers =
{
0,
11,
33,
16000,
1234567,
1000004,
1012009,
1000000000000,
123000014000200
};
for (auto& n : numbers)
cout << n << ": " << NumToWords(n) << endl;
}
|