Skip to content

Latest commit

 

History

History
34 lines (28 loc) · 1.32 KB

117.md

File metadata and controls

34 lines (28 loc) · 1.32 KB

Integer To English

LeetCode Link

    string helper(int num) {
        vector<string> below_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
                                   "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", 
                                   "Eighteen", "Nineteen"};
        vector<string> tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};

        if (num < 20) return below_20[num];
        else if (num < 100) return tens[num / 10] + (num % 10 != 0 ? " " + helper(num % 10) : "");
        else return below_20[num / 100] + " Hundred" + (num % 100 != 0 ? " " + helper(num % 100) : "");
    }
    string numberToWords(int num) {
         if (num == 0) return "Zero";
        
        vector<string> thousands = {"", "Thousand", "Million", "Billion"};
        string result;
        int i = 0;

        while (num > 0) {
            if (num % 1000 != 0) {
                result = helper(num % 1000) + (thousands[i].empty() ? "" : " " + thousands[i]) + " " + result;
            }
            num /= 1000;
            i++;
        }

        // Trim any extra spaces
        while (result.back() == ' ') result.pop_back();
        return result;
    }