【LeetCode.13】 罗马数字转整数

来源:https://leetcode-cn.com/problems/roman-to-integer/

  /**
 * @param String $s
 * @return Integer
 */
function romanToInt($s) {
    $arr = ['I'=>1,'V'=>5,'X'=>10,'L'=>50,'C'=>100,'D'=>500,'M'=>1000];
    $str_arr = str_split($s);
    $num = 0;
    for($i = 0; $i<count($str_arr); $i++){
        // 如果第二个数比第一个数大,则两数相加后减前一个数的二倍
        if($i > 0 && $arr[$str_arr[$i-1]] < $arr[$str_arr[$i]]){
            $num += $arr[$str_arr[$i]] - ($arr[$str_arr[$i-1]]*2);
        }else{
            $num += $arr[$str_arr[$i]];
        }     
    }
    return $num;
}
原文地址:https://www.cnblogs.com/lizhipengvvip/p/13668354.html