[leetcode] 273. Integer to English Words

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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"

分析

题目的意思是:给你一个整数,把它转换成英文单词形式。

  • 这是一道hard类型的题目。
  • 比如一个三位数n,百位数表示为n/100,后两位数一起表示为n%100,十位数表示为n%100/10,个位数表示为n%10;
  • 然后我们看后两位数是否小于20,小于的话直接从数组中取出单词,如果大于等于20的话,则分别将十位和个位数字的单词从两个数组中取出来。
  • 然后再来处理百位上的数字,还要记得加上Hundred。

代码

class Solution {
public:
    string numberToWords(int num) {
        string res=solve(num%1000);
        vector<string> v1={"Thousand", "Million", "Billion"};
        for(int i=0;i<3;i++){
            num/=1000;
            res= num%1000 ? solve(num%1000)+ " "+v1[i]+" "+ res:res;
        }
        while(res.back()==' ') res.pop_back();
        return res.empty() ? "Zero":res;
    }
    string solve(int num){
        vector<string> v1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        vector<string> v2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        string res;
        int a=num/100,b=num%100,c=num%10;
        if(b<20){  // teen
            res=v1[b];
        }else{  //ty
            res=v2[b/10]+ (c ? " "+v1[c]:"");
        }
        if(a>0){  //hundred
            res=v1[a]+" Hundred"+(b ? " "+res:"");
        }
        return res;
    }
};

参考文献

[LeetCode] Integer to English Words 整数转为英文单词

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值