• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
  • This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Leetcode -273- Integer conversion in English

[Blog link]

The path to learning at 🐔

The nuggets home page

[答 案]

Topic link

[making address]

Making the address

[B].

Converts the non-negative integer num to its corresponding English representation.

 

Example 1:

Input: num = 123 output: "One Hundred Twenty Three"Copy the code

Example 2:

Input: num = 12345 output: "Twelve Thousand Three Hundred Forty Five"Copy the code

Example 3:

Input: num = 1234567 output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"Copy the code

Example 4:

Num = 1234567891 "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"Copy the code

Tip:

  • 0 <= num <=
    2 31 2^{31}
    – 1

Idea 1: English level

  • Let’s review our English level
  • Because this question feels really not worth investigating although it is tao Hard
  • But he can’t do it in English even if he is easy
  • 999 in a group, and then pay attention to the special certificates 1-20 and nothing else
  • Enumeration concatenation
class Solution {
    static String[] num2str_small = {
        "Zero"."One"."Two"."Three"."Four"."Five"."Six"."Seven"."Eight"."Nine"."Ten"."Eleven"."Twelve"."Thirteen"."Fourteen"."Fifteen"."Sixteen"."Seventeen"."Eighteen"."Nineteen"
    };
    static String[] num2str_medium = {
        "".""."Twenty"."Thirty"."Forty"."Fifty"."Sixty"."Seventy"."Eighty"."Ninety"
    };
    static String[] num2str_large = {
        "Billion"."Million"."Thousand".""};String num2Str(int x) {
        String ans = "";
        if (x >= 100) {
            ans += num2str_small[x / 100] + " Hundred ";
            x %= 100;
        }
        if (x >= 20) {
            ans += num2str_medium[x / 10] + "";
            x %= 10;
        }
        if(x ! =0) ans += num2str_small[x] + "";
        return ans;
    }
    public String numberToWords(int num) {
        if (num == 0) return num2str_small[0];
        StringBuilder sb = new StringBuilder();
        for (int i = (int)1e9, j = 0; i >= 1; i /= 1000, j++) {
            if (num < i) continue;
            sb.append(num2Str(num / i) + num2str_large[j] + "");
            num %= i;
        }
        while (sb.charAt(sb.length() - 1) = =' ') sb.deleteCharAt(sb.length() - 1);
        returnsb.toString(); }}Copy the code
  • Ps: here with the three leaf big guy’s code, I write this kind of code ugly too, or with three leaf look comfortable

  • Time complexity O(n)

  • Space complexity O(n)