-
Notifications
You must be signed in to change notification settings - Fork 0
/
12. Int to Roman.cpp
149 lines (145 loc) · 3.32 KB
/
12. Int to Roman.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
// Ques->Self explanatory
// range->0<=num<=3999
class Solution {
public:
string intToRoman(int num) {
unordered_map<int,string> lookup;
lookup[1]="I";
lookup[2]="II";
lookup[3]="III";
lookup[4]="IV";
lookup[5]="V";
lookup[6]="VI";
lookup[7]="VII";
lookup[8]="VIII";
lookup[9]="IX";
lookup[10]="X";
lookup[20]="XX";
lookup[30]="XXX";
lookup[40]="XL";
lookup[50]="L";
lookup[60]="LX";
lookup[70]="LXX";
lookup[80]="LXXX";
lookup[90]="XC";
lookup[100]="C";
lookup[200]="CC";
lookup[300]="CCC";
lookup[400]="CD";
lookup[500]="D";
lookup[600]="DC";
lookup[700]="DCC";
lookup[800]="DCCC";
lookup[900]="CM";
lookup[1000]="M";
lookup[2000]="MM";
lookup[3000]="MMM";
int i=0;
string res="";
int val=0;
int rem=0;
while(num>0)
{
rem=num%10;
val=rem*pow(10,i);
i++;
res=lookup[val]+res;
num=num/10;
}
return res;
}
};
//Second solution and much better in space complexity
class Solution {
public:
string intToRoman(int num) {
string ans;
if(num>=1000)
{
int k=num/1000;
while(k--)
ans+='M';
num%=1000;
}
if(num>=500)
{
if(num>=900)
{
ans+="CM";
num%=900;
}
else
{
ans+='D';
num%=500;
}
}
if(num>=100)
{
if(num>=400)
{
ans+="CD";
num%=400;
}
else
{
int k=num/100;
while(k--)
ans+='C';
num%=100;
}
}
if(num>=50)
{
if(num>=90)
{
ans+="XC";
num%=90;
}
else
{
ans+='L';
num%=50;
}
}
if(num>=10)
{
if(num>=40)
{
ans+="XL";
num%=40;
}
else
{
int k=num/10;
while(k--)
ans+='X';
num%=10;
}
}
if(num>=5)
{
if(num==9)
{
ans+="IX";
num%=9;
}
else
{
ans+='V';
num%=5;
}
}
if(num>=1)
{
if(num==4)
ans+="IV";
else
{
while(num--)
ans+='I';
}
}
return ans;
}
};