// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find decimal
// value of a roman character
int charVal(char c)
{
if (c == 'I')
return 1;
if (c == 'V')
return 5;
if (c == 'X')
return 10;
if (c == 'L')
return 50;
if (c == 'C')
return 100;
if (c == 'D')
return 500;
if (c == 'M')
return 1000;
return -1;
}
// Function to convert string representing
// roman number to equivalent decimal value
int romanToDec(string S)
{
// Stores the decimal value
// of the string S
int res = 0;
// Stores the size of the S
int n = S.size();
// Update res
res = charVal(S[n - 1]);
// Traverse the string
for (int i = n - 2; i >= 0; i--) {
if (charVal(S[i]) < charVal(S[i + 1]))
res -= charVal(S[i]);
else
res += charVal(S[i]);
}
// Return res
return res;
}
// Function to convert decimal
// to equivalent roman numeral
string DecToRoman(int number)
{
// Stores the string
string res = "";
// Stores all the digit values of a roman digit
int num[] = { 1, 4, 5, 9, 10, 40, 50,
90, 100, 400, 500, 900, 1000 };
string sym[]
= { "I", "IV", "V", "IX", "X", "XL", "L",
"XC", "C", "CD", "D", "CM", "M" };
int i = 12;
// Iterate while number
// is greater than 0
while (number > 0) {
int div = number / num[i];
number = number % num[i];
while (div--) {
res += sym[i];
}
i--;
}
// Return res
return res;
}
// Function to sort the string
// in descending order of values
// assigned to characters
bool compare(char x, char y)
{
// Return character with
// highest decimal value
int val_x = charVal(x);
int val_y = charVal(y);
return (val_x > val_y);
}
// Function to find largest roman
// value possible by rearranging
// the characters of the string
string findLargest(string S)
{
// Stores all roman characters
set<char> st = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
// Traverse the string
for (auto x : S) {
// If X is not found
if (st.find(x) == st.end())
return "Invalid";
}
sort(S.begin(), S.end(), compare);
// Stores the decimal value
// of the roman number
int N = romanToDec(S);
// Find the roman value equivalent
// to the decimal value of N
string R = DecToRoman(N);
if (S != R)
return "Invalid";
// Return result
return S;
}
// Driver Code
int main()
{
string S = "MCMIV";
cout << findLargest(S);
}