-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem73.cpp
More file actions
60 lines (51 loc) · 1.63 KB
/
problem73.cpp
File metadata and controls
60 lines (51 loc) · 1.63 KB
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
#include <bits/stdc++.h>
using namespace std;
class RoyalScribe {
int num;
vector<string> belowTwenty{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"};
vector<string> tens{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety"};
vector<string> thousands{"", "Thousand", "Million", "Billion"};
// Helper: Convert number < 1000
string helper(int n) {
if (n == 0) return "";
else if (n < 20) return belowTwenty[n] + " ";
else if (n < 100) return tens[n / 10] + " " + helper(n % 10);
else return belowTwenty[n / 100] + " Hundred " + helper(n % 100);
}
public:
void readInput() {
cin >> num;
if (num < 0 || num > INT_MAX) {
cout << "!! Invalid Input !!" << endl;
exit(1);
}
}
string numberToWords() {
if (num == 0) return "Zero";
string res;
int i = 0;
while (num > 0) {
if (num % 1000 != 0) {
res = helper(num % 1000) + thousands[i] + " " + res;
}
num /= 1000;
i++;
}
// Remove trailing spaces
while (!res.empty() && res.back() == ' ') res.pop_back();
return res;
}
void display() {
cout << numberToWords() << endl;
}
};
int main() {
RoyalScribe rs;
rs.readInput();
rs.display();
return 0;
}