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;
    }
};
相关推荐
Dream it possible!4 小时前
LeetCode 面试经典 150_二叉树_二叉树中的最大路径和(77_124_C++_困难)(DFS)
c++·leetcode·面试·二叉树
做怪小疯子8 小时前
LeetCode 热题 100——子串——和为 K 的子数组
算法·leetcode·职场和发展
希望有朝一日能如愿以偿13 小时前
力扣每日一题:仅含1的子串数
算法·leetcode·职场和发展
苏小瀚14 小时前
算法---FloodFill算法和记忆化搜索算法
数据结构·算法·leetcode
少许极端17 小时前
算法奇妙屋(十二)-优先级队列(堆)
数据结构·算法·leetcode·优先级队列··图解算法
Kuo-Teng19 小时前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划
野蛮人6号20 小时前
力扣热题100道之207课程表
算法·leetcode·职场和发展
学学学无无止境20 小时前
力扣-买卖股票的最佳时机
leetcode
Kuo-Teng1 天前
LeetCode 139: Word Break
java·算法·leetcode·职场和发展·word·动态规划
sin_hielo1 天前
leetcode 2654
算法·leetcode