LeetCode - 整数转换英文表示

题目链接:https://leetcode-cn.com/problems/integer-to-english-words/comments/

题目描述

将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。

示例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”

我的思路

  • 这是一道“伪困难”算法题,LeetCode 难度判断很迷,某些简单题反而做得一头包。
  • 这道题主要是要处理各种边界情况比较多一些,另外存英文单词用数组就行,我多此一举用了map,败笔。
  • 思路非常简单,将整数从低位到高位三三分开,分别判断就行。

代码如下:

class Solution {
public:
    string three_numberToWords(int num){
        string en_num = "";
        unordered_map<int, string> en_num1 = {{0, ""}, {1, " One"}, {2, " Two"}, {3, " Three"}, {4, " Four"}, {5, " Five"}, {6, " Six"}, {7, " Seven"}, {8, " Eight"}, {9, " Nine"}, {10, " Ten"}, {11, " Eleven"}, {12, " Twelve"} ,{13, " Thirteen"} ,{14, " Fourteen"} ,{15, " Fifteen"} ,{16, " Sixteen"} ,{17, " Seventeen"} ,{18, " Eighteen"} ,{19, " Nineteen"}};
        unordered_map<int, string> en_num2 = {{0, ""}, {2, " Twenty"}, {3, " Thirty"}, {4, " Forty"}, {5, " Fifty"}, {6, " Sixty"}, {7, " Seventy"}, {8, " Eighty"}, {9, " Ninety"}};
        if(num < 20) return en_num1[num];
        if(num >= 20 && num < 100){
            return en_num2[num/10] + en_num1[num%10];
        }
        if(num >= 100 && num%100 >= 20){
            return en_num1[num/100] + " Hundred" + en_num2[num%100/10] + en_num1[num%100%10];
        }
        if(num >= 100 && num%100 < 20){
            return en_num1[num/100] + " Hundred" + en_num1[num%100];
        }
        return "";
    }
    string numberToWords(int num) {
        string res;
        if(num == 0) return "Zero";
        int billon = num / 1000000000;
        int milion = num % 1000000000 / 1000000;
        int thousand = num % 1000000000 % 1000000 / 1000;
        int simple = num % 1000000000 % 1000000 % 1000;
        if(billon != 0) res += three_numberToWords(billon) + " Billion";
        if(milion != 0) res += three_numberToWords(milion) + " Million";
        if(thousand != 0) res += three_numberToWords(thousand) + " Thousand";
        if(simple != 0) res += three_numberToWords(simple);
        while(res[res.size() - 1] == ' ') res.erase(res.end()-1);
        while(res[0] == ' ') res.erase(res.begin());
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值