Skip to content

Instantly share code, notes, and snippets.

@core-hacked
Created July 13, 2022 13:01
Show Gist options
  • Save core-hacked/9ecb6e28375b8304362cfaf210ffcc67 to your computer and use it in GitHub Desktop.
Save core-hacked/9ecb6e28375b8304362cfaf210ffcc67 to your computer and use it in GitHub Desktop.
Simple integer to roman conversion in PHP
<?php
class Solution {
/**
* @param String $s
* @return Integer
*/
function romanToInt($s) {
$map = [
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000
];
$sum = 0;
$last = 0;
for ($i = strlen($s) - 1; $i >= 0; $i--) {
$cur = $map[$s[$i]];
if ($cur < $last) {
$sum -= $cur;
} else {
$sum += $cur;
}
$last = $cur;
}
return $sum;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment