数字发音

来源:互联网 发布:淘宝外围活动是什么 编辑:程序博客网 时间:2024/04/28 02:25

题目描述

有一个非负整数,请编写一个算法,打印该整数的英文描述。

给定一个int x,请返回一个string,为该整数的英文描述。

测试样例:
1234
返回:"One Thousand,Two Hundred Thirty Four"
class ToString{public:    string toString(int x)    {        // write code here       string base[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",                           "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",                            "Eighteen", "Nineteen"};  //0~19        string tyNum[10] = {"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"};        string bigNum[4] = {"", "Thousand", "Million", "Billion"};        string result;        int k=0;        //将x每三位分成一组进行编码        if(x==0)            return "Zero";        while(x>0)        {            int val=x%1000;            //对三位数进行编码            string temp;            if(base[val/100]!="")  //百位数            {                temp+=base[val/100];                temp+=" Hundred";            }            if(val%100<20)            {                if(!temp.empty())                    temp+=" ";                temp+=base[val%100];            }            else            {                    if(!temp.empty())                    temp+=" ";                    temp+=tyNum[val%100/10];                    if(base[val%10]!="")                    {                        if(!temp.empty())                            temp+=" ";                        temp+=base[val%10];                    }             }            if(!temp.empty()&&bigNum[k]!="")            {                temp+=" ";                temp+=bigNum[k];                if(!result.empty())                    temp+=",";            }            result=temp+result;            k++;            x/=1000;        }        return result;    }}; 

0 0
原创粉丝点击