数字发音

来源:互联网 发布:清华大学化学系 知乎 编辑:程序博客网 时间:2024/06/09 23:15

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

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

测试样例:
1234
返回:"One Thousand,Two Hundred Thirty Four"
思路:判断数的范围,根据范围打印出相应的数值。有一点需要注意,就是逗号的选择,我是加了1个          条件判断,x/N(N=million,billion,thousand,hundred,ten), 判断余数是否是0,进行选择性的​          打印","或""
class ToString {public:    string belowTen[10]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};    string belowTwenty[10]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen",​"Seventeen","Eighteen","Nineteen"};    string belowHundred[10]={"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",​"Eighty","Ninety"};    string toString(int x) {        return fun(x);    }    string fun(int x)        {        string res="";        string t="";        if(x<=0)return "";        else if(x<10)            res=belowTen[x];        else if(x<20)            res=belowTwenty[x-10];        else if(x<100)            res=belowHundred[x/10]+(t=(x%10)>0?" ":"")+belowTen[x%10];        else if(x<1000)            res=fun(x/100)+" Hundred"+(t=(x%100)>0?" ":"")+fun(x%100);        else if(x<1000000)            res=fun(x/1000)+" Thousand"+(t=(x%1000)>0?",":"")+fun(x%1000);        else if(x<1000000000)            res=fun(x/1000000)+" Million"+(t=(x%1000000)>0?",":"")+fun(x%1000000);        else             res=fun(x/1000000000)+" Billion"+(t=(x%1000000000)>0?",":"")+fun(x%1000000000);        return res;    }};


原创粉丝点击