Skip to content

Instantly share code, notes, and snippets.

@mattsches
Created January 30, 2013 08:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattsches/4671552 to your computer and use it in GitHub Desktop.
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.
<?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