<?php

echo romanToInt('III')."\n";
echo romanToInt('LVIII')."\n";
echo romanToInt('MCMXCIV')."\n";
/* Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 */ // Converts the roman numeral to an integer
function romanToInt($roman) {
    $res = $next = 0;
// Letters with their value
 $numbers = ['I'=>1, 'V'=>5, 'X'=>10, 'L'=>50, 'C'=>100, 'D'=>500, 'M'=>1000];

    $len = strlen($roman);
// Loops through letters
for ($i = $len-1; $i >= 0; $i--) {

        $num = $numbers[$roman[$i]];
// Subtracts if the left side letter is less
if ($num < $next) {
            $res -= $num;
        } else {
            $res += $num;
        }
        $next = $num;
    }
    return $res;
}
by ვაჟა ტყემალაძე
2 years ago
Problem Solving
php
0
Pro tip: use ```triple backticks around text``` to write in code fences