Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Program for Converting Roman Numerals to Decimal Lying Between 1 to 3999
Roman numerals are characters used in a numeric notation system based on the ancient Roman system. In this tutorial, we'll convert Roman numeral strings to decimal values in the range 1 to 3999.
Roman Numeral System
Roman numerals follow descending order but use subtractive notation to avoid four consecutive characters. Here are the main symbols
| SYMBOL | VALUE |
|---|---|
| M | 1000 |
| CM | 900 |
| D | 500 |
| CD | 400 |
| C | 100 |
| XC | 90 |
| L | 50 |
| XL | 40 |
| X | 10 |
| IX | 9 |
| V | 5 |
| IV | 4 |
| I | 1 |
Algorithm
The conversion follows these rules
- If current symbol value ? next symbol value, add current value
- If current symbol value
- Process the string from left to right
Example
Let's implement the conversion function ?
<?php
function romanValue($ch) {
$val = -1;
if ($ch == 'I')
$val = 1;
else if ($ch == 'V')
$val = 5;
else if ($ch == 'X')
$val = 10;
else if ($ch == 'L')
$val = 50;
else if ($ch == 'C')
$val = 100;
else if ($ch == 'D')
$val = 500;
else if ($ch == 'M')
$val = 1000;
return $val;
}
function convertRomanToDecimal($str) {
$decValue = 0;
$n = strlen($str);
for ($i = 0; $i < $n; $i++) {
$current = romanValue($str[$i]);
if ($i + 1 < $n) {
$next = romanValue($str[$i + 1]);
if ($current >= $next) {
$decValue += $current;
} else {
$decValue += $next - $current;
$i++;
}
} else {
$decValue += $current;
}
}
return $decValue;
}
// Test examples
$examples = ["DCCCLXXIV", "CMXCIX", "I"];
foreach ($examples as $roman) {
$decimal = convertRomanToDecimal($roman);
echo "Roman: $roman = Decimal: $decimal<br>";
}
?>
Roman: DCCCLXXIV = Decimal: 874 Roman: CMXCIX = Decimal: 999 Roman: I = Decimal: 1
How It Works
- DCCCLXXIV: D(500) + C(100) + C(100) + C(100) + L(50) + X(10) + X(10) + IV(4) = 874
- CMXCIX: CM(900) + XC(90) + IX(9) = 999
- I: I(1) = 1
Time and Space Complexity
The algorithm has O(N) time complexity where N is the string length, and O(1) space complexity as no extra storage is used.
Conclusion
This PHP implementation efficiently converts Roman numerals to decimal values using a single-pass algorithm that handles subtractive notation correctly for the range 1-3999.
Advertisements
