Skip to content

Instantly share code, notes, and snippets.

@patelpreet422
Created July 19, 2018 19:18
Show Gist options
  • Save patelpreet422/7a3cb0b58fdecd70221887f96c420f27 to your computer and use it in GitHub Desktop.
Save patelpreet422/7a3cb0b58fdecd70221887f96c420f27 to your computer and use it in GitHub Desktop.
Roman to decimal and decimal to roman number converter
#include <iostream>
#include <cctype>
#include <array>
#include <unordered_map>
using namespace std;
static unordered_map<char, int> roman_to_dec {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
static unordered_map<int, string> dec_to_roman {
{1, "I"},
{4, "IV"},
{5, "V"},
{9, "IX"},
{10, "X"},
{40, "XL"},
{50, "L"},
{90, "XC"},
{100, "C"},
{400, "CD"},
{500, "D"},
{900, "CM"},
{1000, "M"}
};
int roman_decimal(string roman)
{
int dec{0};
int prev{0};
for(auto it = roman.rbegin(); it != roman.rend(); ++it)
{
int curr = roman_to_dec[toupper(*it)];
if(curr < prev) dec -= curr;
else dec += curr;
prev = curr;
}
cout << roman << ": " << dec << '\n';
return dec;
}
string decimal_roman(int k)
{
int copy_of_k = k;
string roman {};
array<int, 13> mapped_num {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
while(k > 0)
{
int max = 0;
for(int &i: mapped_num)
{
if(i > k) break;
max = i;
}
roman += dec_to_roman[max];
k -= max;
}
cout << copy_of_k << ": " << roman << '\n';
return roman;
}
int main ()
{
int k = 1203;
string roman_str = decimal_roman(k);
roman_decimal(roman_str);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment