The original title is this: the Roman numerals contain the following seven characters: I, V, X, L,c,d and M. i=1,v=5,x=10,l=50,c=100,d=500,m=1000 For example, the Roman numeral 2 writes II, which is two parallel 1. 12 write XII, i.e. X + II. 27 Write the XXVII, that is XX + V + II. Usually, the number of Roman numerals is small and the numbers are on the right side of the large numbers. But there are special cases, such as 4 do not write IIII, but IV. The number 1 is on the left side of the number 5, the number represented is equal to the large number 5 decreases the number 1 gets the value 4. Similarly, the number 9 is represented as IX. This special rule only applies to the following six cases:
- I can be placed on the left of V (5) and X (10) to represent 4 and 9.
- X can be placed on the left of L (50) and C (100) to represent 40 and 90.
- C can be placed on the left of D (500) and M (1000) to represent 400 and 900. The
- converts it to an integer given a Roman number. The input is guaranteed to be within the range of 1 to 3999.
class test
{
public function a5($str)
{
$num = 0;
$num_arr = str_split($str);
$length = count($num_arr);
for ($i=0; $i < $length; $i++)
{
switch ($num_arr[$i])
{
case ‘I‘:
switch ($num_arr[$i+1])
{
case ‘V‘:
$num += 4;
$i++;
break;
case ‘X‘:
$num += 9;
$i++;
break;
default:
$num += 1;
break;
}
break;
case ‘V‘:
$num += 5;
break;
case ‘X‘:
switch ($num_arr[$i+1])
{
case ‘L‘:
$num += 40;
$i++;
break;
case ‘C‘:
$num += 90;
$i++;
break;
default:
$num += 10;
break;
}
break;
case ‘L‘:
$num += 50;
break;
case ‘C‘:
switch ($num_arr[$i+1])
{
case ‘D‘:
$num += 400;
$i++;
break;
case ‘M‘:
$num += 900;
$i++;
break;
default:
$num += 100;
break;
}
break;
case ‘D‘:
$num += 500;
break;
case ‘M‘:
$num += 1000;
break;
default:
break;
}
}
echo $num;
}
}
PHP (4) "Roman numeral to Integer" algorithm problem