Convert Roman Number To Integer - Interview Problem Solving Question | PHP
March 16, 2024 by Primegyan 911
In this post we are going to see a very popular question in interview, Convert roman number to integer. we are going to write a program for that case. we are going to create a function which is accept the Roman string and convert to it's appropriate integer.
The string which i have need to pass that function must be valid roman string.
function romanToInt($s) {
//write all roman numerals and it's correspondence integer
$numerals = array(
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
'' => 0,
);
$num = 0;
$s = str_split($s); //converting string to array
foreach($s as $key => $roman){
if($key > 0 && $numerals[$roman] > $numerals[$s[$key - 1]] && $previous_numeral != $roman){
$num = $num - $numerals[$s[$key - 1]] + $numerals[$roman] - $numerals[$s[$key - 1]];
}else{
$num += $numerals[$roman];
}
}
return $num;
}
This is the solution of convert roman to numerals.