273. Integer to English Words c++

本文介绍了一种算法,用于将非负整数转换为其英文单词表示形式。通过使用预定义的字符串向量,该算法避免了复杂的条件判断,能够高效地处理从个位数到数十亿范围内的整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

273. Integer to English Words

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

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

这道题为了省去条件判断,可以构造两个向量,将下标和英文对应,这样可以省去大量条件判断。

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

需要添加后缀就只是billion,million,thousand,hundred;

因为每3位可以可以看作是1000以内的数,所以可以用递归做;

另外需要特别注意的是整百,整千,整百万,整十亿的数后缀没有空格,所以需要加个判断;

class Solution {
public:
    string numberToWords(int num) 
    {
        string s="";
        vector<string> unit={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        vector<string> tenty = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
        if(num==0) s+="Zero";
        if(num<20) s+=unit[num];
        else if(num<100)
        {
            if(num%10 != 0) s += tenty[num/10] + " " + unit[num%10];
            else s+= tenty[num/10];
        }
        else if(num<1000)
        {
            if(num%100 != 0) s += unit[num/100] + " Hundred " + numberToWords(num%100);
            else s += unit[num/100] + " Hundred";
        }
        else if(num<1000000)
        {
            if(num%1000 != 0) s += numberToWords(num/1000) + " Thousand " + numberToWords(num%1000);
            else s += numberToWords(num/1000) + " Thousand";
        }           
        else if(num<1000000000)
        {
            if(num%1000000 != 0) s += numberToWords(num/1000000) + " Million " + numberToWords(num%1000000);
            else s += numberToWords(num/1000000) + " Million";
        }
        else
        {
            if(num%1000000000 != 0)s += numberToWords(num/1000000000) + " Billion " + numberToWords(num%1000000000);
            else s += numberToWords(num/1000000000) + " Billion";
        }
        return s;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值