273. Integer to English Words

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值