Skip to content

Instantly share code, notes, and snippets.

@blangue
Last active June 24, 2022 14:14
Show Gist options
  • Save blangue/f9368a1c341e288dd87b25ecef55a127 to your computer and use it in GitHub Desktop.
Save blangue/f9368a1c341e288dd87b25ecef55a127 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <iostream>
using namespace std;
class Solution
{
public:
/**
* @brief Extracts the value of a roman number from its char form
* @version 0.1
* @author Bastien LANGUE (bastien.langue@reseau.eseo.fr)
* @date 06.24.2022
* @copyright Copyright (c) 2022
*
* @param c (char) the roman number in char form
* @return (int) The corresponding value
*/
int extractValue(char c)
{
int ret = 0;
switch (c)
{
case 'I':
ret = 1;
break;
case 'V':
ret = 5;
break;
case 'X':
ret = 10;
break;
case 'L':
ret = 50;
break;
case 'C':
ret = 100;
break;
case 'D':
ret = 500;
break;
case 'M':
ret = 1000;
break;
default:
break;
}
return ret;
}
/**
* @brief Runs through the roman number char by char and sums up the result
* @version 0.1
* @author Bastien LANGUE (bastien.langue@reseau.eseo.fr)
* @date 06.24.2022
* @copyright Copyright (c) 2022
*
* @param s (string) The roman number in string form
* @return (int) the resulting value of the roman number
*/
int romanToInt(string s)
{
int res = 0;
for (size_t i = 0; i < s.length(); i++)
{
if (i != s.length() - 1 && extractValue(s.at(i)) < extractValue(s.at(i + 1)))
res -= extractValue(s.at(i));
else
res += extractValue(s.at(i));
}
return res;
}
};

RomanToInt optimal algorithm

Reusable Roman Number to Integer function See reference exercise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment