LeetCode 273: integer to English Words

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 273: integer to English Words相关的知识,希望对你有一定的参考价值。

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

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (num > 0) { 
            if (num % 1000 != 0) {
                result.insert(0, THOUSANDS[i]);
                getString(num % 1000, result);
            }
            i++;
            num /= 1000;
        }
        return result.toString().trim();
    }
    
    private void getString(int num, StringBuilder result) {
        if (num == 0) {
            return;
        } else if (num < 20) {
            result.insert(0, " ");
            result.insert(0, LESS_THAN_20[num]);
        } else if (num < 100) {
            getString(num % 10, result);
            result.insert(0, " ");
            result.insert(0, TENS[num / 10]);
        } else {
            getString(num % 100, result);
            result.insert(0, " Hundred ");
            result.insert(0, LESS_THAN_20[num / 100]);
        }
    }
}

 

 

1. Need check whether each loop of 1000 is 0 or not. Otherwise, it will introduce extra "thousands" words.

2. Each loop needs to count the how many thousands have been processed.

3. Better to use StringBuilder.

以上是关于LeetCode 273: integer to English Words的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 273: integer to English Words

leetcode 273 Integer to English Words

[LeetCode] 273. Integer to English Words

[LeetCode] 273. Integer to English Words 整数转为英文单词

[leetcode]273. Integer to English Words 整数转英文单词

LeetCode 273. Integer to English Words