Clean ans Simple c++ solution


  • 0
    A
    class Solution {
    
    private:
        string getnumTOWordsHelper(int num, vector<string> &ones, vector<string> &Twos)
        {
            string res;
            int n = 0;
            
            n = num / 100;
            num = num % 100;
    
            if (n > 0)
                res.append(ones[n]).append(" Hundred");
            
            if (num >= 20)
            {
                n = num / 10;
                if (res.length() > 0)
                    res.append(" ");
                res.append(Twos[n]);
                
                num = num % 10;
                
                if (num > 0)
                {
                    if (res.length() > 0)
                        res.append(" ");
                    res.append(ones[num]);
                }
            }
            else if (num > 0)
            {
                n = num / 10;
                
                if (n == 0)
                {
                    if (res.length() > 0)
                        res.append(" ");
                    res.append(ones[num]);
                }
                else
                {
                    if (res.length() > 0)
                        res.append(" ");
                    res.append(Twos[num]);
                }
            }
            return res;
        }
    
    public:
    
        string numberToWords(int num) {
            vector<string> ones = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
            vector<string> Twos = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    
            string res;
            vector<string>  triplets;
            
            if (num == 0)
            {
                res.append("Zero");
                return res;
            }
            
            while (num > 0)
            {
                int n = num % 1000;
                num = num / 1000;
                triplets.push_back(getnumTOWordsHelper(n, ones, Twos));
            }
            
            vector<string> milli = {"", "Thousand", "Million", "Billion", "Trillion"};
            
            for (int i = triplets.size() - 1; i >= 0; i--)
            {
                if (res.length() > 0 && triplets[i].size() > 0)
                    res.append(" ");
                    
                res.append(triplets[i]);
                
                if (i > 0 && triplets[i].size() > 0)
                    res.append(" ").append(milli[i]);
            }
            
            return res;
        }
    };
    

Log in to reply
 

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