[hard]273. Integer to English Words

本文介绍了一种将非负整数转换为英文表述的方法。通过详细的代码实现,展示了如何处理千位以上的数值,并确保结果符合英语语法规范。

<span style="font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">273. Integer to English Words</span>

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"


Solution:

It's a super easy problem. Just make sure you have every detail checked.

(Forgot to install a Chinese language input, sorry


Here is my code.

class Solution {
public:
    string num[9] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    string teens[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    string tens[8] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    string units[4] = {"", "Thousand", "Million", "Billion"};

    string under_1000(int x) {
        string ans;
        int hun = x / 100;
        int ten = (x % 100) / 10;
        int sig = x % 10;
        bool first = true;
    
        if (hun) {
            ans += num[hun - 1] + " Hundred";
            first = false;
        }

        if (ten) {
            if (ten >= 2) {
                if (!first)
                    ans += ' ';
                ans += tens[ten - 2];
                if (sig)
                    ans += ' ' + num[sig - 1];
                first = false;
            } else {
                if (!first)
                    ans += ' ';
                ans += teens[sig];
            }
        } else {
            if (sig) {
                if (!first)
                    ans += ' ';
                ans += num[sig - 1];
            }
        }

        return ans;
    }

    string numberToWords(int num) {
        string ans; int count = 0;
        if (!num)
            return "Zero";
        while (num) {
            if (num % 1000 != 0) {
                string str = under_1000(num % 1000);
                if (str != "")
                    if (ans != "")
                        ans = str + ' ' + units[count] + ' ' + ans;
                    else
                        if (units[count] != "")
                            ans = str + ' ' + units[count];
                        else ans = str;
            }
            num /= 1000;
            ++ count;
        }
        return ans;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值