Accepted solution to problem number 13 - conversion of Roman numerals to integers

This commit is contained in:
2025-12-07 23:54:27 +01:00
parent 8e9b1f0fa1
commit 20053ef329
2 changed files with 68 additions and 0 deletions

64
13-roman-to-integer.cpp Normal file
View File

@@ -0,0 +1,64 @@
#include <string>
#include <map>
typedef std::map<std::string, unsigned long> RomanNumeral;
class RomanToIntegerSolution {
private:
RomanNumeral numTable;
public:
int romanToInt(std::string s) {
unsigned long roman(0);
std::string remainder;
remainder.resize(s.length());
unsigned long singleRomanNumerals[255];
singleRomanNumerals['I'] = 1;
singleRomanNumerals['V'] = 5;
singleRomanNumerals['X'] = 10;
singleRomanNumerals['L'] = 50;
singleRomanNumerals['C'] = 100;
singleRomanNumerals['D'] = 500;
singleRomanNumerals['M'] = 1000;
numTable["IV"] = 4;
numTable["IX"] = 9;
numTable["XL"] = 40;
numTable["XC"] = 90;
numTable["CD"] = 400;
numTable["CM"] = 900;
auto len(s.length());
unsigned long j(0);
unsigned long i = 0;
for ( ; i < len-1; i++ ) {
char str[3];
str[0] = s[i];
str[1] = s[i+1];
str[2] = 0;
auto it(numTable.find(str));
if (it != numTable.end()) {
roman += it->second;
i++;
} else {
remainder[j++] = s[i];
remainder[j] = 0;
}
}
if ( i < len ) {
remainder[j++] = s[i];
remainder[j] = 0;
}
for (i = 0; (i < remainder.length()) && (remainder[i] != 0); i++) {
roman += singleRomanNumerals[remainder[i]];
}
return roman;
}
};

View File

@@ -3,6 +3,7 @@
#include "1-two-sum.cpp"
#include "2-add-two-numbers.cpp"
#include "9-palindrome-number.cpp"
#include "13-roman-to-integer.cpp"
int main() {
TwoSumSolution twoSumSolution;
@@ -56,5 +57,8 @@ int main() {
PalindromeNumberSolution p;
std::cout << "Is 1 palindrome? " << p.isPalindrome(1) << std::endl;
RomanToIntegerSolution r;
std::cout << "MCMXCIV = " << r.romanToInt("MCMXCIV") << std::endl;
return 0;
}