zoukankan      html  css  js  c++  java
  • *Integer to English Words

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

    For example,

    123 -> "One Hundred Twenty Three"
    12345 -> "Twelve Thousand Three Hundred Forty Five"
    1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

    Hint:

    1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
    2. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
    3. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
     1 public class Solution {
     2 public String numberToWords(int num) {
     3     if (num == 0) return "Zero";
     4     String[] big= {"", "Thousand", "Million", "Billion"};
     5     String[] small = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
     6     String[] tens = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
     7     String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
     8     StringBuilder res = new StringBuilder();
     9     int count = 0;
    10     while (num != 0) {
    11         int cur = num % 1000;
    12         int o = cur % 10, t = (cur / 10) % 10, h = cur / 100;
    13         StringBuilder tmp = new StringBuilder();
    14         if (h != 0) tmp.append(ones[h] + " Hundred ");
    15         if (t == 1) tmp.append(small[o] + " ");
    16         else {
    17             if (t > 1) tmp.append(tens[t-2] + " ");
    18             if (o > 0) tmp.append(ones[o] + " ");
    19         }
    20         if(tmp.length() != 0) tmp.append(big[count] + " ");
    21         res.insert(0, tmp);
    22         num /= 1000;
    23         count++;
    24     }
    25     return res.toString().trim();
    26 }
    27 }

     https://leetcode.com/discuss/60010/share-my-clean-java-solution

  • 相关阅读:
    IntelliJ Idea 常用快捷键列表
    JSON,字符串,MAP转换
    学习总是无效,是因为你没有稳定的输出系统
    华为离职副总裁徐家骏:透露年薪千万的工作感悟,太震撼了!
    Junit测试Spring应用Dubbo测试框架之-Excel 工具类
    Junit参数化测试Spring应用Dubbo接口
    TestNG参数化测试Spring应用Dubbo接口
    TestNG测试报告美化
    TestNG系列之四: TestNg依赖 dependsOnMethods
    【Java】Java_08 字符型与布尔值
  • 原文地址:https://www.cnblogs.com/hygeia/p/4900111.html
Copyright © 2011-2022 走看看