@@ -117,4 +117,59 @@ Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Th
117
117
return result;
118
118
}
119
119
}
120
+ ```
121
+
122
+ ### Third Time
123
+ * Method 1: String
124
+ ```Java
125
+ class Solution {
126
+ private static final String[] units = new String[]{"", "Thousand", "Million", "Billion"};
127
+ private static final String[] ones = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
128
+ private static String[] tens = new String[]{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
129
+ private static String[] overTens = new String[]{"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
130
+ public String numberToWords(int num) {
131
+ if(num == 0) return "Zero";
132
+ String res = "";
133
+ int bigUnitIndex = 0;
134
+ while(num > 0){
135
+ int cur = num % 1000;
136
+ String curString = parse(cur);
137
+ num /= 1000;
138
+ if(bigUnitIndex == 0){
139
+ res = curString;
140
+ ++bigUnitIndex;
141
+ continue;
142
+ }
143
+ if(curString.length() != 0){
144
+ res = curString + " " + units[bigUnitIndex] + (res.length() == 0 ? "": " ") + res;
145
+ }
146
+ bigUnitIndex++;
147
+ }
148
+ return res;
149
+ }
150
+ private String parse(int num){
151
+ if(num < 10) return ones[num];
152
+ else if(num > 10 && num < 20) return overTens[num - 10];
153
+ else{
154
+ String res = "";
155
+ if(num % 100 > 10 && num % 100 < 20){
156
+ res = overTens[num % 100 - 10];
157
+ num /= 100;
158
+ }else{
159
+ if(num % 10 != 0){
160
+ res = ones[num % 10];
161
+ }
162
+ num /= 10;
163
+ if(num % 10 != 0){
164
+ res = tens[num % 10] + (res.length() == 0 ? "": " " + res);
165
+ }
166
+ num /= 10;
167
+ }
168
+ if(num % 10 != 0){
169
+ res = ones[num % 10] + " Hundred" + (res.length() == 0 ? "": " ") + res;
170
+ }
171
+ return res;
172
+ }
173
+ }
174
+ }
120
175
```
0 commit comments