Roman To Numbers

This algorithm converts roman numerals to decimal numbers.



									/*****Please include following header files*****/
// string
// vector
// locale
/***********************************************/

/*****Please use following namespaces*****/
// std
/*****************************************/

static string ToUpper(const string &str) {
	std::locale loc;
	int strLen = str.length();

	for (int i = 0; i < strLen; ++i)
		std::toupper(str[i], loc);

	return str;
}

static inline string RTrim(const string& s, const string& delimiters = " \f\n\r\t\v") {
	return s.substr(0, s.find_last_not_of(delimiters) + 1);
}

static inline string LTrim(const string& s, const string& delimiters = " \f\n\r\t\v") {
	return s.substr(s.find_first_not_of(delimiters));
}

static inline string Trim(const string& s, const string& delimiters = " \f\n\r\t\v") {
	return LTrim(RTrim(s, delimiters), delimiters);
}

static int RomanToNumber(char romanChar) {
	switch (romanChar)
	{
	case 'I':
		return 1;
	case 'V':
		return 5;
	case 'X':
		return 10;
	case 'L':
		return 50;
	case 'C':
		return 100;
	case 'D':
		return 500;
	case 'M':
		return 1000;
	default:
		break;
	}

	return 0;
}

static int RomanToNumbers(string roman) {
	roman = ToUpper(roman);
	roman = Trim(roman);
	if (roman == "N") return 0;

	int ptr = 0;
	vector<int> values;
	int maxDigit = 1000;
	int romanLen = roman.length();

	while (ptr < romanLen)
	{
		char numeral = roman[ptr];
		int digit = RomanToNumber(numeral);

		int nextDigit = 0;
		if (ptr < romanLen - 1)
		{
			char nextNumeral = roman[ptr + 1];
			nextDigit = RomanToNumber(nextNumeral);

			if (nextDigit > digit)
			{
				maxDigit = digit - 1;
				digit = nextDigit - digit;
				ptr++;
			}
		}

		values.push_back(digit);
		ptr++;
	}

	int total = 0;
	for each(int digit in values)
		total += digit;

	return total;
}
								


Example

									string data = "CDXIX";
int value = RomanToNumbers(data);
								


Output

									419