Task:
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"
Some Questions:
How to spell 1 to 19?
How to spell 20,30,40,...,90?
Solution:
According to the grammar, it reads integer three digits by three digits. So we can convert the Integer into English three digits by three digits.
Thus we need to implement a helper to convert a number within 1000. At last, For every group of three digits, add the suffix of weight to it.
Attention to corner cases!
Code:
class Solution {
const string Mil="Million";
const string Tho="Thousand";
const string Bil="Billion";
const string Hun="Hundred";
string tab[20]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
string tens[10]={"Zero","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
string calc(int n,int w)
{
if(n==0)return "";
string ret="";
if(n>=100)
{
if(ret!="")ret+=" ";
ret+=tab[n/100]+" "+Hun;
}
n%=100;
if(n>0)
{
if(n<20)
{
if(ret!="")ret+=" ";
ret+=tab[n];
}
else
{
if(ret!="")ret+=" ";
if(n%10!=0)
{
ret+=tens[n/10]+" "+tab[n%10];
}
else ret+=tens[n/10];
}
}
if(w==1)
{
ret+=" "+Tho;
}
else if(w==2)
{
ret+=" "+Mil;
}
else if(w==3)
{
ret+=" "+Bil;
}
return ret;
}
public:
string numberToWords(long long num) {
int bit[4];
string ret="";
int len=0;
if(num==0)return "Zero";
while(num)
{
bit[len++]=num%1000;
num/=1000;
}
int i;
for(i=len-1;i>=0;i--)
{
string tmp=calc(bit[i],i);
if(tmp!="")
{
if(ret!="")ret+=" ";
ret+=tmp;
}
}
return ret;
}
};