Created
January 30, 2013 08:06
-
-
Save mattsches/4671552 to your computer and use it in GitHub Desktop.
PHP Roman Numerals Code Kata solution. A collaborative effort of the people @ PHP User Group Rheinhessen, Jan '13.
This file contains 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 | |
/** | |
* Converts Roman numbers to integers | |
*/ | |
class Roman | |
{ | |
/** | |
* @var array | |
*/ | |
protected $d = array( | |
'I' => 1, | |
'V' => 5, | |
'X' => 10, | |
'L' => 50, | |
'C' => 100, | |
'D' => 500, | |
'M' => 1000, | |
); | |
/** | |
* @param string $roman | |
*/ | |
public function toInt($roman) | |
{ | |
$res = 0; | |
$chars = str_split($roman); | |
$length = count($chars); | |
for ($i = 0; $i < $length; $i++) { | |
if (isset($chars[$i+1]) && $this->d[$chars[$i+1]] > $this->d[$chars[$i]]) { | |
$res -= $this->d[$chars[$i]]; | |
} else { | |
$res += $this->d[$chars[$i]]; | |
} | |
} | |
return $res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment