数据转换 273

发布时间 2023-08-28 02:15:37作者: xiaoyongyong
273. Integer to English Words
Hard

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"

Constraints:

  • 0 <= num <= 231 - 1

解法:

1.每000为一个 thousand level

2.单独函数处理每个000level -> helper(num)

   如果是 0,return zero

   如果是 1~19, 直接输出对应map

   如果是 20~99, 输出 十位(20,30,...) + helper(xx % 10)

   如果是 100~999, 输出 百位(one,two...) hundred + helper(xxx % 100)

class Solution {
    private String[] SMALLER_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
    public String numberToWords(int num) {
        //0直接返回 
        if(num == 0) return "Zero";
        //
        String result = "";
        //while loop resvole every 1000
        for(int i = 0; num > 0; i++) {
            if(num % 1000 != 0) result = helper(num % 1000) + THOUSANDS[i] + " " +result;
            num /= 1000;
        }
        return result.trim();
    }
    private String helper(int num) {
        if(num == 0) return "";
        if(num < 20) {
            return SMALLER_THAN_20[num] + " ";
        }
        else if(num < 100) {
            return TENS[num / 10] + " " + helper(num % 10);
        }
        else{
            return SMALLER_THAN_20[num / 100] + " Hundred " + helper(num % 100);
        }
    }
}