Skip to content

Commit 1631dd3

Browse files
committed
Integer to Roman: Trivial.
1 parent b5040eb commit 1631dd3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Medium/012_Integer-to-Roman.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include "../Header.h"
2+
3+
using namespace std;
4+
string intToRoman(int num) {
5+
char item[] = "IVXLCDM";
6+
string result = "";
7+
int pos = 0, digit;
8+
while (num) {
9+
digit = num % 10;
10+
num /= 10;
11+
if (0 < digit && digit < 4) {
12+
string t(digit, item[pos]);
13+
result = t + result;
14+
} else if (digit == 4) {
15+
result = item[pos+1] + result;
16+
result = item[pos] + result;
17+
} else if (digit == 5) {
18+
result = item[pos+1] + result;
19+
} else if (digit != 0 && digit != 9) {
20+
digit -= 5;
21+
string t(digit, item[pos]);
22+
result = item[pos+1] + t + result;
23+
} else if (digit == 9) {
24+
result = item[pos+2] + result;
25+
result = item[pos] + result;
26+
}
27+
pos += 2;
28+
}
29+
return result;
30+
}
31+
int main(int argc, char const *argv[])
32+
{
33+
srand((int)time(NULL));
34+
int num = random(3999);
35+
36+
cout << num << "->" << intToRoman(num) << endl;
37+
return 0;
38+
}

0 commit comments

Comments
 (0)