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;
    }
};
相关推荐
圣保罗的大教堂2 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
Tisfy5 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
tkevinjd8 小时前
图论\dp 两题
leetcode·动态规划·图论
1白天的黑夜112 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼3512 小时前
力扣子集问题C++代码
c++·算法·leetcode
熬了夜的程序员12 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
Miraitowa_cheems12 小时前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
无聊的小坏坏1 天前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
浮灯Foden1 天前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表