# PHP (4) "Roman numeral to Integer" algorithm problem

Source: Internet
Author: User
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.
• Example 1:

Input: "III"
Output: 3

• li>

Example 2:

Input: "IV"
Output: 4

• Example 1:

Output In: "MCMXCIV"
Output: 1994

```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

Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## 11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off，Oct.24-Nov.13 (UTC+8)

Get It Now >

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD