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

LeetCode Integer to English Words

时间:2015-11-05 06:06:15      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/integer-to-english-words/

没三个digit分成一个 unit, 用unitNumber 函数把这三位数换算成数字加上对应的unit.

Note: num = 1,000,000时不可以出现 "One Million Thousand"的情况,所以while循环时 要加上if(rest>0)的限定条件。

AC Java:

 1 public class Solution {
 2     public String numberToWords(int num) {
 3         if(num == 0){
 4             return "Zero";
 5         }
 6         String res = "";
 7         String [] units = {"", " Thousand", " Million", " Billion"};
 8         int i = 0;
 9         while(num>0){
10             int rest = num%1000;
11             if(rest>0){ //error 1,000,000
12                 res = unitNumber(rest) + units[i] + (res.length() == 0 ? "":" "+res);
13             }
14             num/=1000;
15             i++;
16         }
17         return res;
18     }
19     
20     private String unitNumber(int num){
21         String res = "";
22         String [] ten = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
23         String [] twenty = {"Ten","Eleven","Twelve","Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
24         String [] hundred = {"Zero","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"};
25         int a = num/100; 
26         int b = num%100;
27         int c = num%10;
28         
29         if(a>0){
30             res = res+ten[a]+" Hundred";
31         }
32         
33         if(b>=10 && b<20){
34             if(res.length() != 0){
35                 res = res + " ";
36             }
37             res = res + twenty[b%10];
38             return res;
39         }else if(b>=20){
40             b = b/10;
41             if(res.length() != 0){
42                 res = res + " ";
43             }
44             res = res + hundred[b%20];
45         }
46         
47         if(c>0){
48             if(res.length() != 0){
49                 res = res + " ";
50             }
51             res = res + ten[c];
52         }
53         return res;
54     }
55 }

 

LeetCode Integer to English Words

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4937955.html

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