-
Notifications
You must be signed in to change notification settings - Fork 64
/
IntegerToEnglishWords.cpp
152 lines (112 loc) · 3.41 KB
/
IntegerToEnglishWords.cpp
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
// LEETCODE 273. Integer to English Words {HARD}
// Convert a non-negative integer num to its English words representation.
// Example 1:
// Input: num = 123
// Output: "One Hundred Twenty Three"
// Example 2:
// Input: num = 12345
// Output: "Twelve Thousand Three Hundred Forty Five"
// Example 3:
// Input: num = 1234567
// Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
// Constraints:
// 0 <= num <= 231 - 1
### Solution
```
class Solution {
public String ones(int num)
{
switch(num)
{
case 1 : return "One ";
case 2 : return "Two ";
case 3 : return "Three ";
case 4 : return "Four ";
case 5 : return "Five ";
case 6 : return "Six ";
case 7 : return "Seven ";
case 8 : return "Eight ";
case 9 : return "Nine ";
case 10 : return "Ten ";
}
return "";
}
public String tens(int num)
{
switch(num)
{
case 20 : return "Twenty ";
case 30 : return "Thirty ";
case 40 : return "Forty ";
case 50 : return "Fifty ";
case 60 : return "Sixty ";
case 70 : return "Seventy ";
case 80 : return "Eighty ";
case 90 : return "Ninety ";
}
return "";
}
public String less_20(int num)
{
switch(num)
{
case 11 : return "Eleven ";
case 12 : return "Twelve ";
case 13 : return "Thirteen ";
case 14 : return "Fourteen ";
case 15 : return "Fifteen ";
case 16 : return "Sixteen ";
case 17 : return "Seventeen ";
case 18 : return "Eighteen ";
case 19 : return "Nineteen ";
}
return "";
}
public String three(int num)
{
int hundreds = num / 100;
int rest = num % 100;
String res="";
if(hundreds != 0)
res += ones(hundreds) + "Hundred ";
if(rest >= 20)
{
int ties = (rest/10) * 10;
int one = rest % 10;
res += tens(ties) + ones(one);
}
else
{
if(rest <= 10)
res += ones(rest);
else
res+= less_20(rest);
}
return res;
}
public String numberToWords(int num) {
if(num == 0)
return "Zero";
String res = "";
int billions = num / 1000000000;
int millions = (num - (billions * 1000000000)) / 1000000;
int thousands = (num - (billions * 1000000000) - (millions * 1000000)) / 1000;
int rest = (num - (billions * 1000000000) - (millions * 1000000) - (thousands * 1000));
if(billions != 0)
{
res+= three(billions) + "Billion ";
}
if(millions != 0)
{
res+=three(millions) + "Million ";
}
if(thousands !=0 )
{
res+=three(thousands) + "Thousand ";
}
if(rest != 0)
res += three(rest);
return res.substring(0, res.length()-1);
}
}
```