VOOZH about

URL: https://www.geeksforgeeks.org/php/php-program-for-converting-roman-numerals-to-decimal-lying-between-1-to-3999/

⇱ PHP Program to Convert Roman Numerals To Decimal Lying Between 1 to 3999 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP Program to Convert Roman Numerals To Decimal Lying Between 1 to 3999

Last Updated : 23 Jul, 2025

Given a Romal numeral, the task is to find its corresponding decimal value.

Examples

Input: IX
Output: 9
IX is a Roman symbol which represents 9 

Input: XL
Output: 40
XL is a Roman symbol which represents 40

Input: MCMIV
Output: 1904
M is a thousand, CM is nine hundred and IV is four

Roman numerals are based on the following symbols.

SymbolValue
I1
IV4
V5
IX9
X10
XL40
L50
XC90
C100
CD400
D500
CM900
M1000

Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M's first, followed by D's, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows: 

  • I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10).
  • X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred).
  • C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand).

Algorithm to convert Roman Numerals to Integer Number:

  • Split the Roman Numeral string into Roman Symbols (character).
  • Convert each symbol of Roman Numerals into the value it represents.
  • Take symbol one by one from starting from index 0: 
    • If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.
    • else subtract this value by adding the value of next symbol to the running total.

Following is the implementation of the above algorithm: 


Output
Integer form of Roman Numeral is 1904

Complexity Analysis

  • Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is required.
  • Space Complexity: O(1). As no extra space is required.

Please refer complete article on Converting Roman Numerals to Decimal lying between 1 to 3999 for more details!

Comment