数字发音

题目描述

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

给定一个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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值