Skip to content

Instantly share code, notes, and snippets.

@ButchDean
Last active December 29, 2017 20:21
Show Gist options
  • Save ButchDean/ba173657c6429838a81067a8fae50a37 to your computer and use it in GitHub Desktop.
Save ButchDean/ba173657c6429838a81067a8fae50a37 to your computer and use it in GitHub Desktop.
Code to convert Roman Numerals to Decimals. (RN2DEC created by ButchDean72 - https://repl.it/@ButchDean72/RN2DEC)
#include <cstdio>
#include <unordered_map>
#include <vector>
#include <cstring>
#include <memory>
const std::string sample = "MCMLXXII";
struct ROMAN_NUMERALS
{
char letter;
int value;
};
class CRNBase
{
public:
CRNBase(){}
virtual ~CRNBase(){}
protected:
unsigned int FetchRNValue(const char c) const;
private:
std::unordered_map<char, unsigned int> rnValsHash = {{'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}};
};
unsigned int CRNBase::FetchRNValue(const char c) const
{
std::unordered_map<char, unsigned int>::const_iterator itr = rnValsHash.find(c);
if(itr == rnValsHash.end())
return 0;
return itr->second;
}
class CRN2Dec : public CRNBase
{
public:
CRN2Dec(){}
~CRN2Dec(){}
unsigned int DecValue(std::string rnStr);
private:
std::vector<int> values;
};
unsigned int CRN2Dec::DecValue(std::string rnStr)
{
int total = 0, current = 0;
for(std::string::iterator i = rnStr.begin(); i != rnStr.end(); ++i)
{
current = FetchRNValue(*i);
if(values.empty())
{
values.push_back(current);
continue;
}
if(current > values[values.size() - 1])
{
values[values.size() - 1] = current - values[values.size() - 1];
}
else
{
values.push_back(current);
}
}
for(int j = 0; j != values.size(); ++j)
{
total += values[j];
}
return total;
}
int main()
{
std::unique_ptr<CRN2Dec> rn2d(new CRN2Dec());
std::printf("Decimal for %s is %d\n", sample.c_str(), rn2d->DecValue(sample));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment