Leetcode 0273:整数から英語の単語

タイトル説明:

負でない整数numを英語の単語表現に変換します。

中国語の説明:

非負の整数numを対応する英語表現に変換します。

例1:

入力:num = 123
出力:「百二十三」

例2:

入力:num = 12345
出力:「1万2千3百45」

例3:

入力:num = 1234567
出力:「百万二百三十四千五百六十七」

例4:

入力:num = 1234567891
出力:「10億2億3400万5百6億7千8百91」

制約:

0 <= NUM <= 2 31 - 1

時間計算量:OOONNN
分割統治法:
英語によると、桁数は100、1000、Million、Billionです。分割統治法を使用して、数値を異なる桁に解凍し、再帰的に処理することができます。
例:1234567890は、英語の数字で10億2億3400万567千890を意味します。
最もよく聞こえる数字のそれぞれで、各数字は3桁の長さです。
すべての状況を要約します。

  1. = 0は ""を返します;
  2. (0、20)配列を使用して1から0までの英語の単語を格納し、その数の英語の単語を返します
  3. (20、100)配列を使用して、20から90の10の英語を格納し、10桁の英語+1桁の英語を返します。
  4. (100、1000)数百桁、100を超える数値(再帰​​的)(現在の数値/ 100)+ 100桁の単位+数百未満の数値(再帰​​的)(現在の数値%100)
  5. (1000、10 6)数千桁、数千を超える数値(再帰​​的)(現在の数値/ 1000)+千桁+千未満の数値(再帰​​的)(現在の数値%1000)
  6. (10 6、10 9 ]百万桁)桁以上(再帰数百万の数を返す(現在数/ 10 6桁以下(再帰的)の数百万の)+百桁部+数(現在数の10%6
  7. (10 9、2 31-1)億桁は、十億桁を返す以上(再帰)(現在数/ 10 9億+)桁部+億桁以下(再帰)(現在数の10%9
class Solution {
    
    
    private final String[] Less20 = {
    
    "", "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"};
    public String numberToWords(int num) {
    
    
        if (num == 0) return "Zero";
        String res = helper(num);
        return res.trim();
    }

    private String helper(int num) {
    
    
        StringBuilder sb = new StringBuilder();
        if (num < 20) {
    
    
            sb.append(Less20[num]);
        } else if (num < 100) {
    
    
            sb.append(TENS[(num/10)]).append(" ").append(Less20[num % 10]);
        } else if (num < 1000) {
    
    
            sb.append(helper(num / 100)).append(" Hundred ").append(helper(num % 100));
        } else if (num < 1000000) {
    
    
             sb.append(helper(num / 1000)).append(" Thousand ").append(helper(num % 1000));
        } else if (num < 1000000000) {
    
    
             sb.append(helper(num / 1000000)).append(" Million ").append(helper(num %1000000));
        } else {
    
    
             sb.append(helper(num / 1000000000)).append(" Billion ").append(helper(num %1000000000));
        }
        return sb.toString().trim();

    }
}

おすすめ

転載: blog.csdn.net/weixin_43946031/article/details/114109977