No loop, no recursive, 4ms


  • 2
    0
    class Solution {
    public:
        string numberToWords(int num) {
            if (num == 0) return table[num];
            string result;
            int b = num / 1000000000;
            result += read(b, "Billion");
            num %= 1000000000;
            int m = num / 1000000;
            result += read(m, "Million");
            num %= 1000000;
            int k = num / 1000;
            result += read(k, "Thousand");
            num %= 1000;
            result += read(num, "");
            while (result[result.size() - 1] == ' ')
                result.erase(result.end() - 1);
            return result;
        }
        
        string read(int value, const string& suffix) {
            if (value == 0) return "";
            string result;
            int h = value / 100;
            if (h) {
                result += table[h] + " " + table[100] + " ";
            }
            value %= 100;
            int c = value / 10;
            if (c) {
                if (c == 1) {
                    result += table[value] + " ";
                } else {
                    result += table[c * 10] + " ";
                }
            }
            value %= 10;
            if (value && c != 1) {
                result += table[value] + " ";
            }
            return result + suffix + " ";
        }
        
        static unordered_map<int, string> table;
    };
    
    unordered_map<int, string> Solution::table = {
        {0, "Zero"},
        {1, "One"},
        {2, "Two"},
        {3, "Three"},
        {4, "Four"},
        {5, "Five"},
        {6, "Six"},
        {7, "Seven"},
        {8, "Eight"},
        {9, "Nine"},
        {10, "Ten"},
        {11, "Eleven"},
        {12, "Twelve"},
        {13, "Thirteen"},
        {14, "Fourteen"},
        {15, "Fifteen"},
        {16, "Sixteen"},
        {17, "Seventeen"},
        {18, "Eighteen"},
        {19, "Nineteen"},
        {20, "Twenty"},
        {30, "Thirty"},
        {40, "Forty"},
        {50, "Fifty"},
        {60, "Sixty"},
        {70, "Seventy"},
        {80, "Eighty"},
        {90, "Ninety"},
        {100, "Hundred"}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.