程序员面试金典——17.7数字发音

程序员面试金典——17.7数字发音

Solution1:我的答案。要AC这道题真不容易。。。细节注意太多

class ToString {
public:
    vector<string> Digit = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    vector<string> Digit_teen = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    vector<string> Digit_ten = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    vector<string> Digit_big = {"Hundred", "Thousand", "Million", "Billion"};
    string toString(int x) {
        // write code here
        string res;
        int Billion = x/1000000000;
        int Million = (x%1000000000)/1000000;
        int Thousand = (x%1000000)/1000;
        int Hundred = x%1000;//三位数以下的数字
        if(Billion != 0) 
            res += Num_to_Str(Billion) + " " + Digit_big[3];
        if(Million != 0) {
            if(res != "")
                res += "," + Num_to_Str(Million) + " " + Digit_big[2];
            else 
                res += Num_to_Str(Million) + " " + Digit_big[2];
        }
        if(Thousand != 0) {
            if(res != "")
                res += "," + Num_to_Str(Thousand) + " " + Digit_big[1];
            else 
                res += Num_to_Str(Thousand) + " " + Digit_big[1];
        }
        if(Hundred != 0) {
            if(res != "")
                res += "," + Num_to_Str(Hundred);
            else 
                res += Num_to_Str(Hundred);
        }
        return res;
    }

    //把三位数以内的数字转化为英文
    string Num_to_Str(int x) {
        string temp;
        int a = x/100;//百位上的数字
        int b = x%100;//百位以下的数字大小
        int c = x%10; //个位数字
        if(b != 0) { 
            if(b < 20) {
                if(b < 10) 
                    temp = Digit[b];
                else 
                    temp = Digit_teen[b%10];
            }
            else {
                if(b%10 != 0) 
                    temp = Digit_ten[b/10] + " " + Digit[b%10];
                else 
                    temp = Digit_ten[b/10];
            }
        }
        if(a != 0) {
            if(temp != "")
                temp = Digit[a] + " " + Digit_big[0] + " " + temp;
            else 
                temp = Digit[a] + " " + Digit_big[0];
        }
        return temp;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值