Home  >  Article  >  Backend Development  >  Leetcode PHP题解--D82 13. Roman to Integer

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

步履不停
步履不停Original
2019-06-10 09:34:272017browse

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

D82 13. Roman to Integer

Question link

13. Roman to Integer

Question Analysis

Convert the given Roman numerals to Arabic numerals.

Ideas

Use substitution method.

Be careful to replace those that appear consecutively first. For example, rather than replacing I first, replace III first. (php video tutorial)

Final code

<?php
class Solution {    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $ss = str_replace([&#39;CM&#39;,&#39;CD&#39;,&#39;XC&#39;,&#39;XL&#39;,&#39;IX&#39;,&#39;IV&#39;,&#39;M&#39;,&#39;D&#39;,&#39;C&#39;,&#39;L&#39;,&#39;X&#39;,&#39;V&#39;,&#39;I&#39;],[&#39;,900,&#39;,&#39;,400,&#39;,&#39;,90,&#39;,&#39;,40,&#39;,&#39;,9,&#39;,&#39;,4,&#39;,&#39;,1000,&#39;,&#39;,500,&#39;,&#39;,100,&#39;,&#39;,50,&#39;,&#39;,10,&#39;,&#39;,5,&#39;,&#39;,1,&#39;],$s);        return array_sum(array_filter(explode(&#39;,&#39;, $ss)));
    }
}

The above is the detailed content of Leetcode PHP题解--D82 13. Roman to Integer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn