Leetcode 13: Roman to Integers

Here is my solution to this problem in PHP:

class Solution {

    private $v = ['M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1];
    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $n = 0;
        $last = '';
        for ($i=0;$i<strlen($s); $i++) {
            $n += $this->v[$s[$i]];
            if (($s[$i] == 'V' || $s[$i] == 'X') && $last == 'I') { 
                $n = $n - 2;
            } elseif (($s[$i] == 'L' || $s[$i] == 'C') && $last == 'X') {
                $n -= 20;
            } elseif (($s[$i] == 'D' || $s[$i] == 'M') && $last == 'C') {
                $n -= 200;
            }
            $last = $s[$i];
        }
        
        return $n;
    }
}

Leave a Reply