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"
 
class Solution {
public:
    int getDigits(int num,vector<int>& digits)
    {
        int size = 0;
        if(num==0){
            digits.push_back(0);
            size++;
        }
        while(num){
            digits.push_back(num%10);
            size++;
            num/=10;
        }
        return size;
    }
    void digitToStr(int a,int b,int c,string& res,string kvs0[],string kvs1[])
    {
        if(a!=0){
            res += kvs0[a]+" Hundred";
        }
        if(b*10+c<20){
            if(a!=0){
                if(b*10+c!=0){
                    res +=" "+kvs0[b*10+c];
                }
            }else{
                res = kvs0[b*10+c];
            }
        }else{
            if(a!=0){
                res += " "+kvs1[b];
            }else{
                res = kvs1[b];
            }
            if(c!=0){
                res+= " "+kvs0[c];
            }
        }
    }
    string numberToWords(int num) {
        string kvs0[20]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven", "Twelve", "Thirteen", "Fourteen" ,"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        string kvs1[10]={"","Ten","Twenty","Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        string kvs3[4] ={""," Thousand"," Million"," Billion"};
        vector<int> digits;
        int size = getDigits(num,digits);
        string res;
        int k=0;
        for(int i=0;i<size;){
            int c = digits[i++];
            int b = i<size?digits[i++]:0;
            int a = i<size?digits[i++]:0;
            string tmpStr;
            digitToStr(a,b,c,tmpStr,kvs0,kvs1);
          //  cout<<tmpStr<<endl;
            if(tmpStr!="Zero"){
                res = res.empty()?  tmpStr + kvs3[k] : tmpStr + kvs3[k] +" "+ res;    
            }
            k++;
        }
        return res.empty()? "Zero":res;
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/5035724.html