Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active Jan 16, 2022
Embed
What would you like to do?
roman numbers value
// t10e24.rom2int.cpp
// juanfc 2022-01-16
// https://gist.github.com/f47e281ad205395051fd1aaf8f0aa13a
#include <iostream>
using namespace std;
void test(string s);
int main()
{
test("iIi");
test("iv");
test("liv");
return 0;
}
int rom2int(string s);
void test(string s)
{
cout << s << " = " << rom2int(s) << endl;
}
int value(char c);
void tolow(string& s);
int rom2int(string s)
{
tolow(s);
int r = 0;
int prev = 0;
for (int i = s.length()-1; i >= 0; --i) {
int v = value(s[i]);
if (v < prev)
r -= v;
else
r += v;
prev = v;
}
return r;
}
int value(char c)
{
int r = 0;
switch (c) {
case 'i': r = 1; break;
case 'v': r = 5; break;
case 'x': r = 10; break;
case 'l': r = 50; break;
case 'c': r = 100; break;
case 'd': r = 500; break;
case 'm': r = 1000; break;
}
return r;
}
void tolow(string& s)
{
for (int i = 0; i < s.length(); ++i)
s[i] = tolower(s[i]);
}
char tolower(char c)
{
return ('A' <= c and c <= 'Z')? c+'a'-'A' : c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment