Created
April 4, 2022 04:38
-
-
Save sonus/d3f5ea1d05db33ceb1198385540420e0 to your computer and use it in GitHub Desktop.
Roman To Int in PHP
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 Solution { | |
private $romans = [ | |
'I' => 1, | |
'V' => 5, | |
'X' => 10, | |
'L' => 50, | |
'C' => 100, | |
'D' => 500, | |
'M' => 1000 | |
]; | |
/** | |
* @param String $s | |
* @return Integer | |
*/ | |
function romanToInt($s) { | |
$sum = 0; | |
$s_len = strlen($s); | |
for($i=0 ; $i<$s_len ; $i++){ | |
if($this->romans[$s[$i]] < $this->romans[$s[$i+1]]){ | |
$sum += $this->romans[$s[$i+1]] - $this->romans[$s[$i]]; | |
$i++; | |
continue; | |
} | |
$sum += $this->romans[$s[$i]]; | |
} | |
return $sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment