zoukankan      html  css  js  c++  java
  • Leetcode: 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"

    Career Cup 150 Pg 442

    Think of Convert(19,323,984) = Process(19) + "million" + Process(323) + "thousand" + Process(984) + ""

    The Process is a process that generates words representation for integer below 1000

     1 public class Solution {
     2     String[] digits = new String[]{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
     3     String[] teen = new String[]{"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
     4     String[] tens = new String[]{"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
     5     String[] bigs = new String[]{"", "Thousand", "Million", "Billion"};
     6     
     7     public String numberToWords(int num) {
     8         String res = new String();
     9         if (num == 0) return "Zero";
    10         int count = 0;
    11         while (num > 0) {
    12             int belowThousand = num % 1000;
    13             if (belowThousand != 0) {
    14                 res = process(belowThousand) + " " + bigs[count] + " " + res;
    15             }
    16             count++;
    17             num = num / 1000;
    18         }
    19         return res.trim();
    20     }
    21     
    22     public String process(int n) {
    23         String res = new String();
    24         if (n/100 > 0) {
    25             res = digits[n/100-1] + " " + "Hundred" + " ";
    26             n = n%100;
    27         }
    28         if (n>=11 && n<=19) {
    29             res = res + teen[n%10-1];
    30             return res;
    31         }
    32         else if (n/10 > 0) {
    33             res = res + tens[n/10-1] + " ";
    34             n = n%10;
    35         }
    36         if (n > 0) {
    37             res = res + digits[n-1];
    38         }
    39         return res.trim();
    40     }
    41 }
  • 相关阅读:
    第7章 类
    windows查询端口占用以及kill
    判断电脑的系统,以及windows是否是XP
    Promise.all 出现异常时候处理
    [Vue warn]: Failed to mount component: template or render function not defined.
    电脑缺少配置 输入命令解决
    Vue packages version mismatch
    数组里 对象去重
    hexo 创建博客
    查看端口占用,并结束占用端口
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5077313.html
Copyright © 2011-2022 走看看