• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2015-12-26 00:08  neverlandly  阅读(379)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3