码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Integer to English Words

时间:2015-12-26 06:23:05      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Leetcode: Integer to English Words

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5077313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!