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;
    }
};
相关推荐
YoungHong19925 分钟前
面试经典150题[074]:填充每个节点的下一个右侧节点指针 II(LeetCode 117)
leetcode·面试·职场和发展
DanyHope13 分钟前
LeetCode 128. 最长连续序列:O (n) 时间的哈希集合 + 剪枝解法全解析
前端·leetcode·哈希算法·剪枝
元亓亓亓16 分钟前
LeetCode热题100--763. 划分字母区间--中等
算法·leetcode·职场和发展
Dream it possible!16 分钟前
LeetCode 面试经典 150_回溯_全排列(100_46_C++_中等)
c++·leetcode·面试·回溯
鹿角片ljp17 分钟前
力扣206.反转链表-双指针法(推荐)
算法·leetcode·链表
LYFlied33 分钟前
【每日算法】LeetCode 70. 爬楼梯:从递归到动态规划的思维演进
算法·leetcode·面试·职场和发展·动态规划
一起养小猫34 分钟前
LeetCode100天Day2-验证回文串与接雨水
java·leetcode
YoungHong199236 分钟前
面试经典150题[073]:从中序与后序遍历序列构造二叉树(LeetCode 106)
leetcode·面试·职场和发展
业精于勤的牙40 分钟前
浅谈:算法中的斐波那契数(五)
算法·leetcode·职场和发展
LYFlied1 小时前
【每日算法】LeetCode 105. 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·面试·职场和发展