zoukankan      html  css  js  c++  java
  • [leetcode]273. Integer to English Words 整数转英文单词

    Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

    Example 1:

    Input: 123
    Output: "One Hundred Twenty Three"
    Example 2:

    Input: 12345
    Output: "Twelve Thousand Three Hundred Forty Five"

    题目:

    给定一个整数,像check一样将该数字用英文读出来

    思路:

    1. Coz given input is less than 231 - 1, we can say that the highest digit level is billion 

    2. We divide input into N parts, all the parts follow the similar partten of converting.  We use helper function to help recursive call.

    代码:

     1 class Solution {
     2     // coz array index begins at 0, so we use "" to empty a space
     3     private final String[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
     4     private final String[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
     5     private final String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
     6     
     7     public String numberToWords(int num) {
     8         if (num == 0) return "Zero";
     9         return helper(num); 
    10     }
    11     
    12     private String helper(int num) {
    13         String result = new String();
    14         if (num < 10) result = belowTen[num];
    15         else if (num < 20) result = belowTwenty[num -10];
    16         // if num is smaller than 100, keep tens digit and add units digit
    17         else if (num < 100) result = belowHundred[num/10] + " " + helper(num % 10);
    18         // if num is smaller than thousand, call helper to get how many hundreds, call the helper to get the rest digits 
    19         else if (num < 1000) result = helper(num/100) + " Hundred " +  helper(num % 100);
    20         // if num is smaller than million, call helper to get how many thousands, call the helper to get the rest digits 
    21         else if (num < 1000000) result = helper(num/1000) + " Thousand " +  helper(num % 1000);
    22         // if num is smaller than billion, call helper to get how many millions, call the helper to get the rest digits 
    23         else if (num < 1000000000) result = helper(num/1000000) + " Million " +  helper(num % 1000000);
    24         else result = helper(num/1000000000) + " Billion " + helper(num % 1000000000);
    25         return result.trim();
    26     }
    27 }
  • 相关阅读:
    usaco-3.2-butter-passed
    usaco-3.2-msquare-pass
    usaco-3.2-ratios-pass
    usaco-3.2-spin-pass
    usaco-3.2-kimbits-pass
    usaco-3.2-fact4-pass
    usaco-3.1-stamps-pass
    usaco-3.1-contact-pass
    git操作
    spring 用到的设计模式
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9808249.html
Copyright © 2011-2022 走看看