[InterviewBit] Integer To Roman

Integer To Roman

  • Time :
  • Space :
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
int getMaximumDigit(int num) {
return num >= 1000? (num / 1000) * 1000 : num >= 100 ? (num / 100) * 100 : num >= 10 ? (num / 10) * 10 : num % 10;
}
string Solution::intToRoman(int num) {
stringstream solution;
while(num) {
int maximumDigit = getMaximumDigit(num);
if(maximumDigit >= 1000) {
num -= 1000;
solution<<'M';
} else if(maximumDigit >= 900) {
num -= 900;
solution<<"CM";
} else if(maximumDigit >= 500) {
num -= 500;
solution<<'D';
} else if(maximumDigit >= 400) {
num -= 400;
solution<<"CD";
} else if(maximumDigit >= 100) {
num -= 100;
solution<<'C';
} else if(maximumDigit >= 90) {
num -= 90;
solution<<"XC";
} else if(maximumDigit >= 50) {
num -= 50;
solution<<'L';
} else if(maximumDigit >= 40) {
num -= 40;
solution<<"XL";
} else if(maximumDigit >= 10) {
num -= 10;
solution<<'X';
} else if(maximumDigit >= 9) {
num -= 9;
solution<<"IX";
} else if(maximumDigit >= 5) {
num -= 5;
solution<<'V';
} else if(maximumDigit >= 4) {
num -= 4;
solution<<"IV";
} else {
num -= 1;
solution<<'I';
}
}

return solution.str();
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/28/PS/interviewbit/integer-to-roman/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.