LeetCode "Integer to English Words"

本文介绍了一种将整数转换为英文表述的方法。通过定义不同的数值区间对应的英文词汇,如千位、百万位等,并利用这些词汇组合成任意整数的英文表述。文章通过具体的C++代码实现,展示了如何处理各种特殊情况,例如十几到十九之间的数字,以及如何正确地添加“Hundred”等词汇。

Just take care of corner cases.

vector<string> sec3 = { "", "Thousand", "Million", "Billion" };
vector<string> sig = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
vector<string> teen = { "", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen" };
vector<string> ty = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

class Solution
{
    string sec3to(int num)
    {
        int a = num % 10;
        int b = (num / 10) % 10;
        int c = (num / 100) % 10;

        string ret;
        if (b == 1 && a != 0) // teens
        {
            ret += teen[a];
        }
        else if (a == 0 && b != 0) // ty-s
        {
            ret += ty[b];
        }
        else // all other
        {
            if (b > 0) ret += ty[b] + " ";
            if (a > 0) ret += sig[a];
        }
        if (c > 0)
        {
            string hstr = sig[c] + " Hundred";
            if (ret.empty())
                ret = hstr;
            else
                ret = hstr + " " + ret;
        }

        return ret;
    }
public:
    string numberToWords(int num)
    {
        if (num == 0) return "Zero";
        string ret;

        int sec = num % 1000;
        int seci = 0;
        while (num)
        {
            string secstr = sec3to(sec);
            if (!secstr.empty())
                ret = secstr + (seci > 0 ? (" " + sec3[seci] + (ret.empty() ? "" : " " + ret)) : "");

            //
            num /= 1000;
            sec = num % 1000;
            seci++;
        }

        return ret;
    }
};
View Code

转载于:https://www.cnblogs.com/tonix/p/4775485.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值