LeetCode之Integer to English Words

/*按照提示,将原来数字分成3个一组,每个组内数字字符串化,然后再组合起来。*/
class Solution {
public:
    string numberToWords(int num) {
        string units[4] = {"", " Thousand", " Million", " Billion"};
        int i = 0;
        string res;
        while(num != 0){
            int n = num % 1000;
            if(n > 0) res = words(n) + units[i] + (res.empty() ? "" : " " + res);
            num = num / 1000;
            ++i;
        }
        return res.empty() ? "Zero" : res;
    }
    
    string words(int num){
        string res;
        string gewei[10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
        string shiwei[10] = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        string shiji[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        int n = num / 100;
        if(n > 0){
            res = res + gewei[n] + " Hundred";
        }
        n = num % 100;
        if(n >= 10 && n < 20){
            if(!res.empty()) res += " ";
            res = res + shiji[n-10];
            return res;
        }
        else if(n >= 20){
            n = n / 10;
            if(!res.empty()) res += " ";
            res = res + shiwei[n-1];
        }
        n = num % 10;
        if(n > 0){
           if(!res.empty()) res += " ";
            res += gewei[n];
        } 
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值