273 Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than $$2^{31} - 1$$.

For example,

123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Solution

class Solution {
public:
    unordered_map<int, string> dict;
    void createDict() {
        dict[0] = ""; dict[1] = "One"; dict[2] = "Two"; dict[3] = "Three"; dict[4] = "Four";
        dict[5] = "Five"; dict[6] = "Six"; dict[7] = "Seven"; dict[8] = "Eight"; dict[9] = "Nine"; 
        dict[10] = "Ten"; dict[11] = "Eleven"; dict[12] = "Twelve"; dict[13] = "Thirteen"; dict[14] = "Fourteen"; 
        dict[15] = "Fifteen"; dict[16] = "Sixteen"; dict[17] = "Seventeen"; dict[18] = "Eighteen"; dict[19] = "Nineteen";
        dict[20] = "Twenty"; dict[30] = "Thirty"; dict[40] = "Forty"; dict[50] = "Fifty"; dict[60] = "Sixty";
        dict[70] = "Seventy"; dict[80] = "Eighty"; dict[90] = "Ninety";
        return;
    }

    string helper(int num) {
        int i1 = num/100, i2 = num%100;
        string res;
        if ( i1 != 0 ) res = dict[i1] + " Hundred";
        if ( i2 == 0 ) return res;
        if ( i1 != 0 ) res += " ";
        if ( i2 <= 20 ) {
            res += dict[i2];
            return res;
        }
        int i3 = (i2/10)*10, i4 = i2%10;
        res += dict[i3];
        if ( i4 != 0 ) res += " " + dict[i4];
        return res;
    }

    string numberToWords(int num) {
        if ( num == 0 ) return "Zero";
        createDict();
        string s = to_string(num), res;
        reverse(s.begin(), s.end());
        int ns = s.size(), i = 0;
        while ( i < ns ) {
            string tmp = s.substr(i, min(3, ns-i));
            reverse(tmp.begin(), tmp.end());
            string tmp_res = helper(stoi(tmp));
            if ( i == 3 and tmp_res != "" ) tmp_res += " Thousand";
            if ( i == 6 and tmp_res != "" ) tmp_res += " Million";
            if ( i == 9 and tmp_res != "" ) tmp_res += " Billion";
            if ( tmp_res != "" and res != "" ) res = " " + res;
            res = tmp_res + res;
            i += 3;
        }
        return res;
    }
};

Notes
Pay attention to "0"s and spaces in the output.

results matching ""

    No results matching ""