12ms C++ solution


  • 0
    I
    class Solution {
    map<int, string> ones = {
        {1, " One"},
        {2, " Two"},
        {3, " Three"},
        {4, " Four"},
        {5, " Five"},
        {6, " Six"},
        {7, " Seven"},
        {8, " Eight"},
        {9, " Nine"},
        {10, " Ten"}
    };
    map<int, string> teens = {
        {11, " Eleven"},
        {12, " Twelve"},
        {13, " Thirteen"},
        {14, " Fourteen"},
        {15, " Fifteen"},
        {16, " Sixteen"},
        {17, " Seventeen"},
        {18, " Eighteen"},
        {19, " Nineteen"},
    };
    map<int, string> twos = {
        {20, " Twenty"},
        {30, " Thirty"},
        {40, " Forty"},
        {50, " Fifty"},
        {60, " Sixty"},
        {70, " Seventy"},
        {80, " Eighty"},
        {90, " Ninety"}
    };
    map<int, string> sp = {
        {0, ""},
        {1, " Thousand"},
        {2, " Million"},
        {3, " Billion"}
    };
    public:
    string calcTwo(int n) {
        string res = "";
        if (n > 0 && n < 11) {
            res = ones.find(n)->second;
        } else if (n >= 11 && n <= 19) {
            res = teens.find(n)->second;
        } else if (n > 19) {
            int oneDigit = n%10;
            int twoDigit = n/10;
    
            if (twoDigit >= 2 && twoDigit <= 9)
                res = twos.find(twoDigit*10)->second;
    
            if (oneDigit > 0 && oneDigit < 11)
                res = res + ones.find(oneDigit)->second;
        }
        return res;
    }
    
    string calcThree(int n, int delim) {
        string res = "";
        if (n > 0) {
            int x = n%100;
            res = calcTwo(x);
            n /= 100;
            if (n > 0 && n < 10) {
                res = ones.find(n)->second + " Hundred" + res;
            }
        }
        return res;
    }
    
    string numberToWords(int num) {
        if (num == 0) return "Zero";
        int d = 1000, term = 0;
        string res = "";
    
        while(num > 0) {
            int x = num%d;
            if (num%d > 0) {
                res = calcThree(num%d, term) + sp.find(term)->second + res;
            }
            num = num/d;
            term++;
        }
    
        res.erase(0, 1);
        return res;
    }
     };

Log in to reply
 

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