0273. Integer to English Words

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

Description

Convert a non-negative integer num to its English words representation.

Example 1:

**Input:** num = 123
**Output:** "One Hundred Twenty Three"

Example 2:

**Input:** num = 12345
**Output:** "Twelve Thousand Three Hundred Forty Five"

Example 3:

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

Example 4:

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

Constraints:

  • 0 <= num <= 231 - 1

ac

it's very heavy dirty code writing.

class Solution {
    private String[] lessThan20 = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] tens = new String[]{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] thousands = new String[]{"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num) {
        // edge cases
        if (num == 0) return "Zero";

        String res = "";

        int kth = 0;
        while (num > 0) {
            int tmp = num % 1000;
            if (tmp != 0) {
                res = read3(tmp) + " " + thousands[kth] + " " + res;
            }
            num /= 1000;
            kth++;
        }

        return res.trim();
    }

    private String read3(int num) {
        StringBuilder sb = new StringBuilder();

        int d1 = num % 10;
        int d2 = (num % 100) / 10;
        int d3 = num / 100;

        // read hundred
        if (d3 != 0) {
            sb.append(lessThan20[d3] + " Hundred");
        }

        // read tens
        if (d2 != 0) {
            int last2digit = num % 100;
            if (last2digit < 20) {
                sb.append(" " + lessThan20[last2digit]);
                return sb.toString().trim();
            } else {
                sb.append(" " + tens[d2]);
            }
        }

        // read one
        if (d1 != 0) {
            sb.append(" " + lessThan20[d1]);
        }

        return sb.toString().trim();
    }
}

/*
2,147,483,647
1st: 647
2nd: 483
3rd: 147
4th: 2

*/

Last updated