Created
July 13, 2022 13:01
-
-
Save core-hacked/9ecb6e28375b8304362cfaf210ffcc67 to your computer and use it in GitHub Desktop.
Simple integer to roman conversion in PHP
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 | |
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