Leetcode PHP题解--D82 13. Roman to Integer

D82 13. Roman to Integer

题目链接

13. Roman to Integer

题目分析

将给定的罗马数字转换成阿拉伯数字。

思路

用替换法。

要注意,先替换连续出现的那些。例如,比先替换I,要先替换III

最终代码

<?php
class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $ss = str_replace(['CM','CD','XC','XL','IX','IV','M','D','C','L','X','V','I'],[',900,',',400,',',90,',',40,',',9,',',4,',',1000,',',500,',',100,',',50,',',10,',',5,',',1,'],$s);
        return array_sum(array_filter(explode(',', $ss)));
    }
}
复制代码

若觉得本文章对你有用,欢迎用爱发电资助。

猜你喜欢

转载自blog.csdn.net/weixin_34283445/article/details/91372578