LeetCode——273. 整数转换英文表示(Integer to English Words)[中等]——分析及代码(C++)

LeetCode——273. 整数转换英文表示[Integer to English Words][中等]——分析及代码[C++]

一、题目

将非负整数 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"

示例 4:

输入:num = 1234567891
输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

提示:

  • 0 <= num <= 2^31 - 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-to-english-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、分析及代码

1. 迭代

(1)思路

根据题目要求,以每 3 位为一个单位,迭代地进行表示。

(2)代码

class Solution {
    
    
public:
    vector<string> singles = {
    
    "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};//个位[1,9]
    vector<string> teens = {
    
    "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};//[10,19]
    vector<string> tens = {
    
    "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};//十位[1,9]
    vector<string> thousands = {
    
    "", "Thousand", "Million", "Billion"};//单位

    string numberToWords(int num) {
    
    
        if (num == 0) {
    
    
            return "Zero";
        }
        string str;//英文表示的字符串
        for (int i = 3; i >= 0; i--) {
    
    //从大到小遍历各单位
            int unit = pow(1000, i), curNum = num / unit;//单位值,当前单位下的数值
            if (curNum > 0) {
    
    
                //百位表示
                if (curNum / 100 > 0) {
    
    
                    str += singles[curNum / 100] + " Hundred ";
                }
                curNum %= 100;
                //十位和个位表示
                if (curNum >= 20) {
    
    
                    str += tens[curNum / 10] + " ";
                    if (curNum % 10 > 0) {
    
    
                        str += singles[curNum % 10] + " ";
                    }
                } else if (curNum >= 10) {
    
    
                    str += teens[curNum % 10] + " ";
                } else if (curNum > 0) {
    
    
                    str += singles[curNum] + " ";
                }
                //单位表示
                if (i > 0) {
    
    
                    str += thousands[i] + " ";
                }
            }
            num %= unit;//过滤当前单位已完成表示的部分
        }
        str.pop_back();//删除最后一个空格
        return str;
    }
};

(3)结果

执行用时 :0 ms,在所有 C++ 提交中击败了 100.00% 的用户;
内存消耗 :7.2 MB,在所有 C++ 提交中击败了 38.45% 的用户。

三、其他

暂无。

猜你喜欢

转载自blog.csdn.net/zml66666/article/details/120695471