$str = "MCMXCIV";
print_r(romanToInt($str));
function romanToInt($s) {
$arr = array(
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000
);
$res = 0;
$len = strlen($s);
for ($i = 0; $i < $len; $i ++) {
if (isset($arr[$s[$i]])) {
if (!isset($arr[$s[$i+1]]) || $arr[$s[$i]] >= $arr[$s[$i+1]]) {
$res += $arr[$s[$i]];
}else {
$res -= $arr[$s[$i]];
}
}
}
return $res;
}
网友评论