-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathWordsToNumber.java
343 lines (285 loc) · 12.6 KB
/
WordsToNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package com.thealgorithms.conversions;
import java.io.Serial;
import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
A Java-based utility for converting English word representations of numbers
into their numeric form. This utility supports whole numbers, decimals,
large values up to trillions, and even scientific notation where applicable.
It ensures accurate parsing while handling edge cases like negative numbers,
improper word placements, and ambiguous inputs.
*
*/
public final class WordsToNumber {
private WordsToNumber() {
}
private enum NumberWord {
ZERO("zero", 0),
ONE("one", 1),
TWO("two", 2),
THREE("three", 3),
FOUR("four", 4),
FIVE("five", 5),
SIX("six", 6),
SEVEN("seven", 7),
EIGHT("eight", 8),
NINE("nine", 9),
TEN("ten", 10),
ELEVEN("eleven", 11),
TWELVE("twelve", 12),
THIRTEEN("thirteen", 13),
FOURTEEN("fourteen", 14),
FIFTEEN("fifteen", 15),
SIXTEEN("sixteen", 16),
SEVENTEEN("seventeen", 17),
EIGHTEEN("eighteen", 18),
NINETEEN("nineteen", 19),
TWENTY("twenty", 20),
THIRTY("thirty", 30),
FORTY("forty", 40),
FIFTY("fifty", 50),
SIXTY("sixty", 60),
SEVENTY("seventy", 70),
EIGHTY("eighty", 80),
NINETY("ninety", 90);
private final String word;
private final int value;
NumberWord(String word, int value) {
this.word = word;
this.value = value;
}
public static Integer getValue(String word) {
for (NumberWord num : values()) {
if (word.equals(num.word)) {
return num.value;
}
}
return null;
}
}
private enum PowerOfTen {
THOUSAND("thousand", new BigDecimal("1000")),
MILLION("million", new BigDecimal("1000000")),
BILLION("billion", new BigDecimal("1000000000")),
TRILLION("trillion", new BigDecimal("1000000000000"));
private final String word;
private final BigDecimal value;
PowerOfTen(String word, BigDecimal value) {
this.word = word;
this.value = value;
}
public static BigDecimal getValue(String word) {
for (PowerOfTen power : values()) {
if (word.equals(power.word)) {
return power.value;
}
}
return null;
}
}
public static String convert(String numberInWords) {
if (numberInWords == null) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.NULL_INPUT, "");
}
ArrayDeque<String> wordDeque = preprocessWords(numberInWords);
BigDecimal completeNumber = convertWordQueueToBigDecimal(wordDeque);
return completeNumber.toString();
}
public static BigDecimal convertToBigDecimal(String numberInWords) {
String conversionResult = convert(numberInWords);
return new BigDecimal(conversionResult);
}
private static ArrayDeque<String> preprocessWords(String numberInWords) {
String[] wordSplitArray = numberInWords.trim().split("[ ,-]");
ArrayDeque<String> wordDeque = new ArrayDeque<>();
for (String word : wordSplitArray) {
if (word.isEmpty()) {
continue;
}
wordDeque.add(word.toLowerCase());
}
if (wordDeque.isEmpty()) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.NULL_INPUT, "");
}
return wordDeque;
}
private static void handleConjunction(boolean prevNumWasHundred, boolean prevNumWasPowerOfTen, ArrayDeque<String> wordDeque) {
if (wordDeque.isEmpty()) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, "");
}
String nextWord = wordDeque.pollFirst();
String afterNextWord = wordDeque.peekFirst();
wordDeque.addFirst(nextWord);
Integer number = NumberWord.getValue(nextWord);
boolean isPrevWordValid = prevNumWasHundred || prevNumWasPowerOfTen;
boolean isNextWordValid = number != null && (number >= 10 || afterNextWord == null || "point".equals(afterNextWord));
if (!isPrevWordValid || !isNextWordValid) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, "");
}
}
private static BigDecimal handleHundred(BigDecimal currentChunk, String word, boolean prevNumWasPowerOfTen) {
boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0;
if (currentChunk.compareTo(BigDecimal.TEN) >= 0 || prevNumWasPowerOfTen) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word);
}
if (currentChunkIsZero) {
currentChunk = currentChunk.add(BigDecimal.ONE);
}
return currentChunk.multiply(BigDecimal.valueOf(100));
}
private static void handlePowerOfTen(List<BigDecimal> chunks, BigDecimal currentChunk, BigDecimal powerOfTen, String word, boolean prevNumWasPowerOfTen) {
boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0;
if (currentChunkIsZero || prevNumWasPowerOfTen) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word);
}
BigDecimal nextChunk = currentChunk.multiply(powerOfTen);
if (!(chunks.isEmpty() || isAdditionSafe(chunks.getLast(), nextChunk))) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word);
}
chunks.add(nextChunk);
}
private static BigDecimal handleNumber(Collection<BigDecimal> chunks, BigDecimal currentChunk, String word, Integer number) {
boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0;
if (number == 0 && !(currentChunkIsZero && chunks.isEmpty())) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word);
}
BigDecimal bigDecimalNumber = BigDecimal.valueOf(number);
if (!currentChunkIsZero && !isAdditionSafe(currentChunk, bigDecimalNumber)) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word);
}
return currentChunk.add(bigDecimalNumber);
}
private static void handlePoint(Collection<BigDecimal> chunks, BigDecimal currentChunk, ArrayDeque<String> wordDeque) {
boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0;
if (!currentChunkIsZero) {
chunks.add(currentChunk);
}
String decimalPart = convertDecimalPart(wordDeque);
chunks.add(new BigDecimal(decimalPart));
}
private static void handleNegative(boolean isNegative) {
if (isNegative) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.MULTIPLE_NEGATIVES, "");
}
throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_NEGATIVE, "");
}
private static BigDecimal convertWordQueueToBigDecimal(ArrayDeque<String> wordDeque) {
BigDecimal currentChunk = BigDecimal.ZERO;
List<BigDecimal> chunks = new ArrayList<>();
boolean isNegative = "negative".equals(wordDeque.peek());
if (isNegative) {
wordDeque.poll();
}
boolean prevNumWasHundred = false;
boolean prevNumWasPowerOfTen = false;
while (!wordDeque.isEmpty()) {
String word = wordDeque.poll();
switch (word) {
case "and" -> {
handleConjunction(prevNumWasHundred, prevNumWasPowerOfTen, wordDeque);
continue;
}
case "hundred" -> {
currentChunk = handleHundred(currentChunk, word, prevNumWasPowerOfTen);
prevNumWasHundred = true;
continue;
}
default -> {
}
}
prevNumWasHundred = false;
BigDecimal powerOfTen = PowerOfTen.getValue(word);
if (powerOfTen != null) {
handlePowerOfTen(chunks, currentChunk, powerOfTen, word, prevNumWasPowerOfTen);
currentChunk = BigDecimal.ZERO;
prevNumWasPowerOfTen = true;
continue;
}
prevNumWasPowerOfTen = false;
Integer number = NumberWord.getValue(word);
if (number != null) {
currentChunk = handleNumber(chunks, currentChunk, word, number);
continue;
}
switch (word) {
case "point" -> {
handlePoint(chunks, currentChunk, wordDeque);
currentChunk = BigDecimal.ZERO;
continue;
}
case "negative" -> {
handleNegative(isNegative);
}
default -> {
}
}
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNKNOWN_WORD, word);
}
if (currentChunk.compareTo(BigDecimal.ZERO) != 0) {
chunks.add(currentChunk);
}
BigDecimal completeNumber = combineChunks(chunks);
return isNegative ? completeNumber.multiply(BigDecimal.valueOf(-1))
:
completeNumber;
}
private static boolean isAdditionSafe(BigDecimal currentChunk, BigDecimal number) {
int chunkDigitCount = currentChunk.toString().length();
int numberDigitCount = number.toString().length();
return chunkDigitCount > numberDigitCount;
}
private static String convertDecimalPart(ArrayDeque<String> wordDeque) {
StringBuilder decimalPart = new StringBuilder(".");
while (!wordDeque.isEmpty()) {
String word = wordDeque.poll();
Integer number = NumberWord.getValue(word);
if (number == null) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD_AFTER_POINT, word);
}
decimalPart.append(number);
}
boolean missingNumbers = decimalPart.length() == 1;
if (missingNumbers) {
throw new WordsToNumberException(WordsToNumberException.ErrorType.MISSING_DECIMAL_NUMBERS, "");
}
return decimalPart.toString();
}
private static BigDecimal combineChunks(List<BigDecimal> chunks) {
BigDecimal completeNumber = BigDecimal.ZERO;
for (BigDecimal chunk : chunks) {
completeNumber = completeNumber.add(chunk);
}
return completeNumber;
}
}
class WordsToNumberException extends RuntimeException {
@Serial private static final long serialVersionUID = 1L;
enum ErrorType {
NULL_INPUT("'null' or empty input provided"),
UNKNOWN_WORD("Unknown Word: "),
UNEXPECTED_WORD("Unexpected Word: "),
UNEXPECTED_WORD_AFTER_POINT("Unexpected Word (after Point): "),
MISSING_DECIMAL_NUMBERS("Decimal part is missing numbers."),
MULTIPLE_NEGATIVES("Multiple 'Negative's detected."),
INVALID_NEGATIVE("Incorrect 'negative' placement"),
INVALID_CONJUNCTION("Incorrect 'and' placement");
private final String message;
ErrorType(String message) {
this.message = message;
}
public String formatMessage(String details) {
return "Invalid Input. " + message + (details.isEmpty() ? "" : details);
}
}
public final ErrorType errorType;
WordsToNumberException(ErrorType errorType, String details) {
super(errorType.formatMessage(details));
this.errorType = errorType;
}
public ErrorType getErrorType() {
return errorType;
}
}