int范围内数字的英文读法

题目

给定一个整数,打印该整数的英文描述。
示例 1:

输入: 123
输出: “One Hundred Twenty Three”

示例 2:

输入: 12345
输出: “Twelve Thousand Three Hundred Forty Five”

示例 3:

输入: 1234567
输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

示例 4:

输入: 1234567891
输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

解题思路

  • 3 3 3 个一组分开求数值大小。注意:特殊处理 0 0 0 - 20 20 20,还有 100 100 100 也需要注意 。
  • i n t int int 数字最大 10 10 10 位到 2 2 2 m i l l i o n million million

代码

class Solution {
public:
    string numberToWords(int num) {
        if(num == 0){
            return "Zero";
        }
        //先将负数变为正数
        long n = num;
        string ans = "";
        if(n < 0){
            n = -num;
            ans += "Negative";
        }
        //找三次
        string str[4] = {"Billion", "Million", "Thousand", ""};
        int t = 1000000000;
        for(int i = 0; i < 4; ++i){
            cout << n / t << endl;
            string temp = getThreeNum(n / t);
            n %= t;
            t /= 1000;
            if(temp != ""){
                if(ans != ""){
                    ans += " ";
                }
                ans += temp;
                if(str[i] != ""){
                    ans += " ";
                }
                ans += str[i];
            }
        }
        
        return ans;
    }

    string number[21] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"};

    string numTen[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

    string getThreeNum(int num){
        if(num == 0){
            return "";
        }
        string ans = "";
        if(num / 100 != 0){
            ans += number[num / 100];
            ans += " ";
            ans += "Hundred";
            num %= 100;
        }
        if(num == 0){
            return ans;
        }
        if(num <= 20){
            if(ans != ""){
                ans += " ";
            }
            ans += number[num];
        }
        else{
            if(ans != ""){
                ans += " ";
            }
            ans += numTen[num / 10];
            num %= 10;
            if(num != 0){
                ans += " ";
                ans += number[num];
            }
        }
        return ans;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值