Leetcode 273. 整数转换英文表示

将非负整数 num 转换为其对应的英文表示。

示例 1:

输入:num = 123

输出:"One Hundred Twenty Three"

示例 2:

输入:num = 12345

输出:"Twelve Thousand Three Hundred Forty Five"

示例 3:

输入:num = 1234567

输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

提示:

0 <= num <= 231 - 1

cpp 复制代码
class Solution {
public:
    
    string num0_19[20] = {
        "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
        "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
    };
    string num20_90[8] = {
        "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
    };
    string num1000[5] = {
        "Billion ", "Million ", "Thousand ", "",
    };

    string get(int x) {
        string res;
        if (x >= 100) {
            res += num0_19[x / 100] + " Hundred ";
            x %= 100;
        }
        if (x >= 20) {
            res += num20_90[x / 10 - 2] + " ";
            x %= 10;
            if (x) res += num0_19[x] + ' ';
        } else if (x) {
            res += num0_19[x] + ' ';
        }
        return res;
    }

    string numberToWords(int num) {
        if(!num) return "Zero";
        string res;
        for(int i = 1e9, j = 0; i >= 1; i /= 1000, j ++ )
            if(num >= i) {
                res += get(num / i) + num1000[j];
                num %= i;
            }
        res.pop_back();
        return res;
    }
};
相关推荐
ゞ 正在缓冲99%…8 小时前
leetcode2826.将三个组排序
算法·leetcode·动态规划
微笑尅乐12 小时前
洗牌算法讲解——力扣384.打乱数组
算法·leetcode·职场和发展
天选之女wow12 小时前
【代码随想录算法训练营——Day48】单调栈——42.接雨水、84.柱状图中最大的矩形
算法·leetcode
仰泳的熊猫13 小时前
LeetCode:773. 滑动谜题
数据结构·c++·算法·leetcode
夏鹏今天学习了吗13 小时前
【LeetCode热题100(50/100)】岛屿数量
算法·leetcode·职场和发展
墨染点香13 小时前
LeetCode 刷题【134. 加油站】
算法·leetcode·职场和发展
Voyager_415 小时前
算法学习记录08——并归的应用(LeetCode[315])
学习·算法·leetcode
海梨花16 小时前
【力扣Hot100】刷题日记
算法·leetcode·1024程序员节
chonbw17 小时前
226.翻转二叉树
算法·leetcode
sprintzer19 小时前
10.16-10.25力扣计数刷题
算法·leetcode