Easy understanding C++ solution


  • 1
    R
    class Solution {
    public:
        vector<string> unit1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        vector<string> unit2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
            
        string number2string(int num)
        {
            string ret;
            if (num >= 100)
            {
                ret += unit1[num/100] + " Hundred" + " ";
                num = num % 100;
            }
            if (num >= 20)
            {
                ret += unit2[num/10] + " ";
                num = num % 10;
            }
            if (0<num && num<20)
                ret += unit1[num] + " ";
                
            return ret;
        }
        
        string numberToWords(int num) 
        {
            string ret;
            if (num >= 1000000000)
            {
                ret += number2string(num/1000000000) + "Billion" + " ";
                num = num % 1000000000;
            }
            if (num >= 1000000)
            {
                ret += number2string(num/1000000) + "Million" + " ";
                num = num % 1000000;
            }
            if (num >= 1000)
            {
                ret += number2string(num/1000) + "Thousand" + " ";
                num = num % 1000;
            }
            if (num < 1000)
            {
                ret += number2string(num);
            }
            
            if (ret.empty())
                return "Zero";
                
            return ret.substr(0, ret.size()-1);;
        }
    };

Log in to reply
 

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