4ms Compact C++ Solution


  • 0
    H
    class Solution {
    public:
        string convert1(int d) {
            string word[10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
            return word[d];
        }
        string convert2(int t) {
            string word[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
            return word[t];
        }
        string convert2a(int t) {
            string word[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
            return word[t];
        }
        string convert3(int n) {
            string s = "";
            int h = n/100;
            bool sp = false;
            if (h >= 1) {
                s += convert1(h);
                s += " ";
                s += "Hundred";
                sp = true;
            }
            n %= 100;
            int t = n/10;
            if (t >= 2) {
                if (sp) s += " ";
                s += convert2(t);
                sp = true;
            } else 
            if (t == 1) {
                if (sp) s += " ";
                s += convert2a(n-10);
                return s;
            }
            
            n %= 10;
            if (n >= 1) {
                if (sp) s += " ";
                s += convert1(n);
            }
            return s;
        }
        string numberToWords(int num) {
            if (!num) return "Zero";
            string str = convert3(num%1000);
            num /= 1000;
            if (num%1000) str = convert3(num%1000) + " Thousand" + ((str == "") ? "" : " ") + str;
            num /= 1000;
            if (num%1000) str = convert3(num%1000) + " Million" + ((str == "") ? "" : " ") + str;
            num /= 1000;
            if (num%1000) str = convert3(num%1000) + " Billion" + ((str == "") ? "" : " ") + str;
            return str;
        }
    };

Log in to reply
 

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