-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintToRoman
More file actions
35 lines (34 loc) · 892 Bytes
/
intToRoman
File metadata and controls
35 lines (34 loc) · 892 Bytes
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
string intToRoman(int num) {
char romanChar[] = {'I','V','X','L','C','D','M'};
string res;
int i = 6, factor = 1000;
while(num != 0)
{
helper(num / factor, &romanChar[i], res);
i -= 2;
num %= factor;
factor /= 10;
}
return res;
}
void helper(int k, char romanChar[], string &res)
{// 0 <= k <= 9
if(k <= 0);
else if(k <= 3)
res.append(k, romanChar[0]);
else if(k == 4)
{
res.push_back(romanChar[0]);
res.push_back(romanChar[1]);
}
else if(k <= 8)
{
res.push_back(romanChar[1]);
res.append(k-5, romanChar[0]);
}
else if(k == 9)
{
res.push_back(romanChar[0]);
res.push_back(romanChar[2]);
}
}