-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInteger to words
68 lines (54 loc) · 1.88 KB
/
Integer to words
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
//Integer to words
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine().trim());
while(tc-- > 0) {
int n = Integer.parseInt(br.readLine().trim());
String ans = new Solution().convertToWords(n);
System.out.println("\"" + ans + "\"");
}
}
}
class Solution {
String convertToWords(int n) {
if(n == 0) {
return "Zero";
}
int[] values = {
1000000000, 1000000, 1000, 100, 90, 80, 70,
60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
};
String[] words = {
"Billion", "Million", "Thousand", "Hundred",
"Ninety", "Eighty", "Seventy", "Sixty", "Fifty",
"Forty", "Thirty", "Twenty", "Nineteen",
"Eighteen", "Seventeen", "Sixteen", "Fifteen",
"Fourteen", "Thirteen", "Twelve", "Eleven",
"Ten", "Nine", "Eight", "Seven", "Six", "Five",
"Four", "Three", "Two", "One"
};
return convertToWordsRec(n, values, words);
}
static String convertToWordsRec(int n, int[] values, String[] words) {
String res = "";
for(int i = 0; i < values.length; i++) {
int value = values[i];
String word = words[i];
if(n >= value) {
if(n >= 100) {
res += convertToWordsRec(n / value, values, words) + " ";
}
res += word;
if(n % value > 0) {
res += " " + convertToWordsRec(n % value, values, words);
}
return res;
}
}
return res;
}
}