Leetcode 273 Solution

This article provides solution to leetcode question 273 (integer-to-english-words)

https://leetcode.com/problems/integer-to-english-words

Solution

class Solution {
public:
    string numberToWords(int num) {
        static const char* digits1[10] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
        static const char* digits2[10] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
        static const char* digits3[10] = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

        if (num < 10)
            return digits1[num];
        else if (num < 20)
            return digits2[num - 10];
        else if (num < 100 && num % 10 == 0)
            return digits3[num / 10];
        else if (num < 100)
            return digits3[num / 10] + string(" ") + numberToWords(num % 10);
        else if (num < 1000)
            return numberToWords(num / 100) + (num % 100 == 0 ? string(" Hundred") : string(" Hundred ") + numberToWords(num % 100));
        else if (num < 1000000)
            return numberToWords(num / 1000) + (num % 1000 == 0 ? string(" Thousand") : string(" Thousand ") + numberToWords(num % 1000));
        else if (num < 1000000000)
            return numberToWords(num / 1000000) + (num % 1000000 == 0 ? string(" Million") : string(" Million ") + numberToWords(num % 1000000));
        else
            return numberToWords(num / 1000000000) + (num % 1000000000 == 0 ? string(" Billion") : string(" Billion ") + numberToWords(num % 1000000000));
    }
};