Skip to content

Commit cac8a02

Browse files
authored
Merge pull request #529 from ishikasinha-d/integer-to-roman
Create integer_to_roman.cpp
2 parents 35892cb + f7f98da commit cac8a02

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Strings/integer_to_roman.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Convert an integer number n to roman number.
2+
3+
#include<bits/stdc++.h>
4+
#define fl(i,a,b) for(i=a;i<b;i++)
5+
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
6+
using namespace std;
7+
typedef long long int ll;
8+
9+
string int_to_roman(ll n)
10+
{
11+
string str="";
12+
// store all base values in vector in descending order
13+
vector <int > v ={1000,900,500,400,100,90,50,40,10,9,5,4,1};
14+
15+
// store roman numeral equivalent of each base value using map
16+
map <int, string> m ={{1000,"M"}, {900,"CM"},{500,"D"},{400,"CD"},{100,"C"},{90,"XC"},{50,"L"},{40,"XL"},{10,"X"},{9,"IX"},{5,"V"},{4,"IV"},{1,"I"}};
17+
18+
//now find the largest base value
19+
//dividing the number and repeat the symbol accordingly
20+
21+
for(auto x: v)
22+
{
23+
if(n>0)
24+
{
25+
int i= n/x;
26+
n= n%x;
27+
while(i--)
28+
str+= m[x]; //repeating the correspoding roman symbol
29+
}
30+
else
31+
return str;
32+
}
33+
return str;
34+
}
35+
36+
int main()
37+
{
38+
fast;
39+
40+
ll n; cin>>n;
41+
cout<<int_to_roman(n);
42+
43+
return 0;
44+
45+
}

0 commit comments

Comments
 (0)