Compact C++ solution, 4ms, beats 71.68%


  • 0
    K
    class Solution {
    public:
        string numberToWords(int num) {
            int billion  = 1000000000;
            int million  = 1000000;
            int thousand = 1000;
            
            string result;
            int vbillion = num / billion;
            if (0 < vbillion)
                result += Convert0_999(vbillion) + " Billion";
            
            int vmillion = (num % billion) / million;
            if (0 < vmillion)
                result += (result.empty() ? "" : " ") + Convert0_999(vmillion) + " Million";
            
            int vthousand = (num % million) / thousand;
            if (0 < vthousand)
                result += (result.empty() ? "" : " ") + Convert0_999(vthousand) + " Thousand";
            
            int vrest = num % thousand;
            if (0 < vrest)
                result += (result.empty() ? "" : " ") + Convert0_999(vrest);
            
            if (result.empty())
                result = "Zero";
            
            return result;
        }
        
        string Convert0_999(int v) {
            static vector<string> table1 = {
                "",
                "One",
                "Two",
                "Three",
                "Four",
                "Five",
                "Six",
                "Seven",
                "Eight",
                "Nine",
                "Ten",
                "Eleven",
                "Twelve",
                "Thirteen",
                "Fourteen",
                "Fifteen",
                "Sixteen",
                "Seventeen",
                "Eighteen",
                "Nineteen"
            };
            
            static vector<string> table2 = {
                "",
                "",
                "Twenty",
                "Thirty",
                "Forty",
                "Fifty",
                "Sixty",
                "Seventy",
                "Eighty",
                "Ninety"
            };
            
            string result;
            int v100 = (v / 100) % 10;
            if (0 < v100)
                result = table1[v100] + " Hundred";
            
            int v11 = v % 100;
            if (0 < v11 && v11 < 20) 
                result += (result.empty() ? "" : " ") + table1[v11];
            else if (v11 >= 20) {
                int v10 = (v % 100) / 10;
                int v1 = v % 10;
                result += (result.empty() ? "" : " ") + table2[v10];
                if (0 < v1)
                    result += (result.empty() ? "" : " ") + table1[v1];
            }
            
            return result;
        }
    };

Log in to reply
 

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