Skip to content

Instantly share code, notes, and snippets.

@tommymarshall
Created August 25, 2014 19:17
Show Gist options
  • Save tommymarshall/1076d9a08a90c54d890f to your computer and use it in GitHub Desktop.
Save tommymarshall/1076d9a08a90c54d890f to your computer and use it in GitHub Desktop.
Converts roman numerals to numbers.
<?php
class RomanNumeralsConverter
{
protected static $mappings = [
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
];
public function convert($number)
{
$result = 0;
while(strlen($number) > 1) {
$current = static::$mappings[$number[0]];
$next = static::$mappings[$number[1]];
if ($current >= $next) {
$result += $current;
$number = substr($number, 1);
} else {
$result += $next - $current;
$number = substr($number, 2);
}
}
if ($number) {
$result += static::$mappings[$number];
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment