Leetcode 273: 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"

 

 

 1 public class Solution {
 2     public string NumberToWords(int num) {
 3         if (num == 0) return "Zero";
 4         
 5         var units = new string[] {" Billion", " Million", " Thousand", ""};
 6 
 7         InitMap();
 8         
 9         var sb = new StringBuilder();
10         var unit = 1000000000;
11         
12         for (int i = 0; i < units.Length; i++)
13         {
14             if (num >= unit)
15             {
16                 if (sb.Length > 0) sb.Append(" ");
17                 sb.Append(ConvertHundred(num / unit));
18                 num %= unit;
19                 sb.Append(units[i]);
20             }  
21             
22             unit /= 1000;
23         }
24         
25         return sb.ToString();        
26     }
27     
28     private Dictionary<int, string> map = new Dictionary<int, string>();
29     
30     private void InitMap()
31     {
32         map[1] = "One";
33         map[2] = "Two";
34         map[3] = "Three";
35         map[4] = "Four";
36         map[5] = "Five";
37         map[6] = "Six";
38         map[7] = "Seven";
39         map[8] = "Eight";
40         map[9] = "Nine";
41         map[10] = "Ten";
42         map[11] = "Eleven";
43         map[12] = "Twelve";
44         map[13] = "Thirteen";
45         map[14] = "Fourteen";
46         map[15] = "Fifteen";
47         map[16] = "Sixteen";
48         map[17] = "Seventeen";
49         map[18] = "Eighteen";
50         map[19] = "Nineteen";
51         map[20] = "Twenty";
52         map[30] = "Thirty";
53         map[40] = "Forty";
54         map[50] = "Fifty";
55         map[60] = "Sixty";
56         map[70] = "Seventy";
57         map[80] = "Eighty";
58         map[90] = "Ninety";
59     }
60     
61     private string ConvertHundred(int num)
62     {
63         var sb = new StringBuilder();
64         
65         if (num >= 100)
66         {
67             sb.Append(map[num/100]);
68             sb.Append(" Hundred");
69             num %= 100;
70         }
71         
72         if (num >= 20)
73         {
74             if (sb.Length > 0) sb.Append(" ");
75             sb.Append(map[(num/10) * 10]);
76             num %= 10;
77         }
78         
79         if (num > 0)
80         {
81             if (sb.Length > 0) sb.Append(" ");
82             sb.Append(map[num]);
83         }
84         
85         return sb.ToString();
86     }
87 }

 

posted @ 2018-01-31 02:03  逸朵  阅读(124)  评论(0)    收藏  举报