273. Integer to English Words

Problem:

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

Solutions:

class Solution {
public:
    string numberToWords(int num) {
        if (num == 0)   return "Zero";
        string ret;
        if (num >= 1000000000) {
            ret += lessThousand(num / 1000000000) + " Billion ";
            num = num % 1000000000;
        }
        if (num >= 1000000) {
            ret += lessThousand(num / 1000000) + " Million ";
            num = num % 1000000;
        }

        if (num >= 1000) {
            ret += lessThousand(num / 1000) + " Thousand ";
            num = num % 1000;
        }

        ret += lessThousand(num);

        if (ret.back() == ' ') {
            ret.pop_back();
        }

        return ret;
    }

private:
    string lessThousand(int num) {
        string twenty[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        string hundred[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        string ret;
        if (num / 100 > 0) {
            ret = twenty[num / 100] + " " + "Hundred ";
            num = num % 100;
        }

        if (num >= 20) {
            ret += hundred[num/10 - 2] + " ";
            num = num % 10;
        }

        if (num > 0) {
            ret += twenty[num];
        }

        if (ret.length() > 0 && ret.back() == ' ') {
            ret.pop_back();
        }

        return ret;
    }
};

results matching ""

    No results matching ""