Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active November 22, 2023 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/f47e281ad205395051fd1aaf8f0aa13a to your computer and use it in GitHub Desktop.
Save juanfal/f47e281ad205395051fd1aaf8f0aa13a to your computer and use it in GitHub Desktop.
roman numbers value
// t11e25.rom2int.cpp
// juanfc 2023-11-22
// 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