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;
    }
};
相关推荐
Ethan-D2 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 733 题:图像渲染
算法·leetcode·职场和发展
FMRbpm4 小时前
树的练习6--------938.二叉搜索树的范围和
数据结构·c++·算法·leetcode·职场和发展·新手入门
多米Domi0114 小时前
0x3f 第35天 电脑硬盘坏了 +二叉树直径,将有序数组转换为二叉搜索树
java·数据结构·python·算法·leetcode·链表
想逃离铁厂的老铁4 小时前
Day45 >> 115、不同的子序列 + 583. 两个字符串的删除操作 + 72. 编辑距离
算法·leetcode
程序员-King.5 小时前
day144—递归—平衡二叉树(LeetCode-110)
算法·leetcode·二叉树·递归
老鼠只爱大米5 小时前
LeetCode经典算法面试题 #739:每日温度(单调栈、动态规划等多种实现方案详解)
算法·leetcode·面试·动态规划·单调栈·每日温度
老鼠只爱大米6 小时前
LeetCode经典算法面试题 #394:字符串解码(递归、双栈、迭代构建等五种实现方案详解)
算法·leetcode·面试·递归··字符串解码
漫随流水6 小时前
leetcode算法(513.找树左下角的值)
数据结构·算法·leetcode·二叉树
AlenTech7 小时前
152. 乘积最大子数组 - 力扣(LeetCode)
算法·leetcode·职场和发展