Created
August 25, 2014 19:17
-
-
Save tommymarshall/1076d9a08a90c54d890f to your computer and use it in GitHub Desktop.
Converts roman numerals to numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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