Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIConverting Roman Numerals to Decimal lying between 1 to 3999

Converting Roman Numerals to Decimal lying between 1 to 3999

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

Example : 

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
Recommended Practice

Roman numerals are based on the following symbols.  

SYMBOL       VALUE
  I            1
  IV           4
  V            5
  IX           9
  X            10
  XL           40
  L            50
  XC           90
  C            100
  CD           400
  D            500
  CM           900 
  M            1000

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:  

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

Following is the implementation of the above algorithm: 

C




// Program to convert Roman
// Numerals to Numbers
#include <stdio.h>
#include <string.h>
 
// This function returns value
// of a Roman symbol
int value(char r)
{
    if (r == 'I')
        return 1;
    if (r == 'V')
        return 5;
    if (r == 'X')
        return 10;
    if (r == 'L')
        return 50;
    if (r == 'C')
        return 100;
    if (r == 'D')
        return 500;
    if (r == 'M')
        return 1000;
 
    return -1;
}
 
// Returns decimal value of
// roman numaral
int romanToDecimal(char str[])
{
    // Initialize result
    int res = 0;
 
    // Traverse given input
    for (int i = 0; i < strlen(str); i++)
    {
        // Getting value of symbol s[i]
        int s1 = value(str[i]);
 
        if (i + 1 < strlen(str))
        {
            // Getting value of symbol s[i+1]
            int s2 = value(str[i + 1]);
 
            // Comparing both values
            if (s1 >= s2)
            {
                // Value of current symbol
                // is greater or equal to
                // the next symbol
                res = res + s1;
            }
            else
            {
                // Value of current symbol is
                // less than the next symbol
                res = res + s2 - s1;
                i++;
            }
        }
        else {
            res = res + s1;
        }
    }
    return res;
}
 
// Driver Code
int main()
{
    // Considering inputs given are valid
    char str[10] = "MCMIV";
    printf("Integer form of Roman Numeral is %d",romanToDecimal(str));
 
 
    return 0;
}


C++




// Program to convert Roman
// Numerals to Numbers
#include <bits/stdc++.h>
using namespace std;
 
// This function returns value
// of a Roman symbol
int value(char r)
{
    if (r == 'I')
        return 1;
    if (r == 'V')
        return 5;
    if (r == 'X')
        return 10;
    if (r == 'L')
        return 50;
    if (r == 'C')
        return 100;
    if (r == 'D')
        return 500;
    if (r == 'M')
        return 1000;
 
    return -1;
}
 
// Returns decimal value of
// roman numaral
int romanToDecimal(string& str)
{
    // Initialize result
    int res = 0;
 
    // Traverse given input
    for (int i = 0; i < str.length(); i++) {
        // Getting value of symbol s[i]
        int s1 = value(str[i]);
 
        if (i + 1 < str.length()) {
            // Getting value of symbol s[i+1]
            int s2 = value(str[i + 1]);
 
            // Comparing both values
            if (s1 >= s2) {
                // Value of current symbol
                // is greater or equal to
                // the next symbol
                res = res + s1;
            }
            else {
                // Value of current symbol is
                // less than the next symbol
                res = res + s2 - s1;
                i++;
            }
        }
        else {
            res = res + s1;
        }
    }
    return res;
}
 
// Driver Code
int main()
{
    // Considering inputs given are valid
    string str = "MCMIV";
    cout << "Integer form of Roman Numeral is "
         << romanToDecimal(str) << endl;
 
    return 0;
}


Java




// Program to convert Roman
// Numerals to Numbers
import java.util.*;
 
public class RomanToNumber {
    // This function returns
    // value of a Roman symbol
    int value(char r)
    {
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
 
    // Finds decimal value of a
    // given roman numeral
    int romanToDecimal(String str)
    {
        // Initialize result
        int res = 0;
 
        for (int i = 0; i < str.length(); i++) {
            // Getting value of symbol s[i]
            int s1 = value(str.charAt(i));
 
            // Getting value of symbol s[i+1]
            if (i + 1 < str.length()) {
                int s2 = value(str.charAt(i + 1));
 
                // Comparing both values
                if (s1 >= s2) {
                    // Value of current symbol
                    // is greater or equalto
                    // the next symbol
                    res = res + s1;
                }
                else {
                    // Value of current symbol is
                    // less than the next symbol
                    res = res + s2 - s1;
                    i++;
                }
            }
            else {
                res = res + s1;
            }
        }
 
        return res;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        RomanToNumber ob = new RomanToNumber();
 
        // Considering inputs given are valid
        String str = "MCMIV";
        System.out.println("Integer form of Roman Numeral"
                           + " is "
                           + ob.romanToDecimal(str));
    }
}


Python




# Python program to convert Roman Numerals
# to Numbers
 
# This function returns value of each Roman symbol
 
 
def value(r):
    if (r == 'I'):
        return 1
    if (r == 'V'):
        return 5
    if (r == 'X'):
        return 10
    if (r == 'L'):
        return 50
    if (r == 'C'):
        return 100
    if (r == 'D'):
        return 500
    if (r == 'M'):
        return 1000
    return -1
 
 
def romanToDecimal(str):
    res = 0
    i = 0
 
    while (i < len(str)):
 
        # Getting value of symbol s[i]
        s1 = value(str[i])
 
        if (i + 1 < len(str)):
 
            # Getting value of symbol s[i + 1]
            s2 = value(str[i + 1])
 
            # Comparing both values
            if (s1 >= s2):
 
                # Value of current symbol is greater
                # or equal to the next symbol
                res = res + s1
                i = i + 1
            else:
 
                # Value of current symbol is greater
                # or equal to the next symbol
                res = res + s2 - s1
                i = i + 2
        else:
            res = res + s1
            i = i + 1
 
    return res
 
 
# Driver code
print("Integer form of Roman Numeral is"),
print(romanToDecimal("MCMIV"))


C#




// C# Program to convert Roman
// Numerals to Numbers
using System;
 
class GFG {
    // This function returns value
    // of a Roman symbol
    public virtual int value(char r)
    {
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
 
    // Finds decimal value of a
    // given roman numeral
    public virtual int romanToDecimal(string str)
    {
        // Initialize result
        int res = 0;
 
        for (int i = 0; i < str.Length; i++) {
            // Getting value of symbol s[i]
            int s1 = value(str[i]);
 
            // Getting value of symbol s[i+1]
            if (i + 1 < str.Length) {
                int s2 = value(str[i + 1]);
 
                // Comparing both values
                if (s1 >= s2) {
                    // Value of current symbol is greater
                    // or equalto the next symbol
                    res = res + s1;
                }
                else {
                    res = res + s2 - s1;
                    i++; // Value of current symbol is
                    // less than the next symbol
                }
            }
            else {
                res = res + s1;
                i++;
            }
        }
 
        return res;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        GFG ob = new GFG();
 
        // Considering inputs given are valid
        string str = "MCMIV";
        Console.WriteLine("Integer form of Roman Numeral"
                          + " is "
                          + ob.romanToDecimal(str));
    }
}
 
// This code is contributed by Shrikant13


PHP




<?php
// Program to convert Roman
// Numerals to Numbers
 
// This function returns
// value of a Roman symbol
function value($r)
{
    if ($r == 'I')
        return 1;
    if ($r == 'V')
        return 5;
    if ($r == 'X')
        return 10;
    if ($r == 'L')
        return 50;
    if ($r == 'C')
        return 100;
    if ($r == 'D')
        return 500;
    if ($r == 'M')
        return 1000;
 
    return -1;
}
 
// Returns decimal value
// of roman numeral
function romanToDecimal(&$str)
{
    // Initialize result
    $res = 0;
 
    // Traverse given input
    for ($i = 0; $i < strlen($str); $i++)
    {
        // Getting value of
        // symbol s[i]
        $s1 = value($str[$i]);
 
        if ($i+1 < strlen($str))
        {
            // Getting value of
            // symbol s[i+1]
            $s2 = value($str[$i + 1]);
 
            // Comparing both values
            if ($s1 >= $s2)
            {
                // Value of current symbol
                // is greater or equal to
                // the next symbol
                $res = $res + $s1;
            }
            else
            {
                $res = $res + $s2 - $s1;
                $i++; // Value of current symbol is
                      // less than the next symbol
            }
        }
        else
        {
            $res = $res + $s1;
            $i++;
        }
    }
    return $res;
}
 
// Driver Code
 
// Considering inputs
// given are valid
$str ="MCMIV";
echo "Integer form of Roman Numeral is ",
              romanToDecimal($str), "\n";
 
// This code is contributed by ajit
?>


Javascript




<script>
// Program to convert Roman
// Numerals to Numberspublic
    // This function returns
    // value of a Roman symbol
    function value(r) {
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
 
    // Finds decimal value of a
    // given roman numeral
    function romanToDecimal( str)
    {
     
        // Initialize result
        var res = 0;
 
        for (i = 0; i < str.length; i++)
        {
         
            // Getting value of symbol s[i]
            var s1 = value(str.charAt(i));
 
            // Getting value of symbol s[i+1]
            if (i + 1 < str.length) {
                var s2 = value(str.charAt(i + 1));
 
                // Comparing both values
                if (s1 >= s2) {
                    // Value of current symbol
                    // is greater or equalto
                    // the next symbol
                    res = res + s1;
                }
                else
                {
                 
                    // Value of current symbol is
                    // less than the next symbol
                    res = res + s2 - s1;
                    i++;
                }
            } else {
                res = res + s1;
            }
        }
 
        return res;
    }
 
    // Driver Code
     
        // Considering inputs given are valid
        var str = "MCMIV";
        document.write("Integer form of Roman Numeral"
        + " is " + romanToDecimal(str));
 
// This code is contributed by umadevi9616
</script>


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.

Another solution –

C++




// Program to convert Roman
// Numerals to Numbers
#include <bits/stdc++.h>
using namespace std;
 
// This function returns value
// of a Roman symbol
int romanToDecimal(string& str)
{
    map<char, int> m;
    m.insert({ 'I', 1 });
    m.insert({ 'V', 5 });
    m.insert({ 'X', 10 });
    m.insert({ 'L', 50 });
    m.insert({ 'C', 100 });
    m.insert({ 'D', 500 });
    m.insert({ 'M', 1000 });
    int sum = 0;
    for (int i = 0; i < str.length(); i++)
    {
        /*If present value is less than next value,
          subtract present from next value and add the
          resultant to the sum variable.*/
        if (m[str[i]] < m[str[i + 1]])
        {
            sum+=m[str[i+1]]-m[str[i]];
            i++;
            continue;
        }
        sum += m[str[i]];
    }
    return sum;
}
 
// Driver Code
int main()
{
    // Considering inputs given are valid
    string str = "MCMIV";
    cout << "Integer form of Roman Numeral is "
         << romanToDecimal(str) << endl;
 
    return 0;
}


Java




// Program to convert Roman
// Numerals to Numbers
import java.util.Map;
import java.util.HashMap;
 
class GFG{
     
private static final Map<Character,
                         Integer> roman = new HashMap<Character,
                                                      Integer>()
{{
    put('I', 1);
    put('V', 5);
    put('X', 10);
    put('L', 50);
    put('C', 100);
    put('D', 500);
    put('M', 1000);
}};
 
// This function returns value
// of a Roman symbol
private static int romanToInt(String s)
{
    int sum = 0;
    int n = s.length();
     
    for(int i = 0; i < n; i++)
    {
         
        // If present value is less than next value,
        // subtract present from next value and add the
        // resultant to the sum variable.
        if (i != n - 1 && roman.get(s.charAt(i)) <
                          roman.get(s.charAt(i + 1)))
        {
            sum += roman.get(s.charAt(i + 1)) -
                   roman.get(s.charAt(i));
            i++;
        }
        else
        {
            sum += roman.get(s.charAt(i));
        }
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
     
      // Considering inputs given are valid
    String input = "MCMIV";
     
    System.out.print("Integer form of Roman Numeral is " +
                     romanToInt(input));
}
}
 
// This code is contributed by rahuldevgarg


Python3




# Program to convert Roman
# Numerals to Numbers
roman = {}
roman['I'] = 1
roman['V'] = 5
roman['X'] = 10
roman['L'] = 50
roman['C'] = 100
roman['D'] = 500
roman['M'] = 1000
     
# This function returns value
# of a Roman symbol
def romanToInt(s):
   sum = 0
   n = len(s)
 
   i = 0
   while i < n :
 
      # If present value is less than next value,
      # subtract present from next value and add the
      # resultant to the sum variable.
      # print(roman[s[i]],roman[s[i+1]])
      if (i != n - 1 and roman[s[i]] < roman[s[i + 1]]):
         sum += roman[s[i + 1]] - roman[s[i]]
         i += 2
         continue
      else:
         sum += roman[s[i]]
      i += 1
   return sum
 
# Driver Code
     
# Considering inputs given are valid
input = "MCMIV"
 
print(f"Integer form of Roman Numeral is {romanToInt(input)}")
 
# This code is contributed by shinjanpatra


C#




// Program to convert Roman
// Numerals to Numbers
using System;
using System.Collections.Generic;
 
public class GFG {
 
  static  Dictionary<char, int> roman = new Dictionary<char, int>();
 
 
  // This function returns value
  // of a Roman symbol
  public static int romanToInt(String s) {
    int sum = 0;
    int n = s.Length;
 
    for (int i = 0; i < n; i++) {
 
      // If present value is less than next value,
      // subtract present from next value and add the
      // resultant to the sum variable.
      if (i != n - 1 && roman[s[i]] < roman[s[i + 1]]) {
        sum += roman[s[i + 1]] - roman[s[i]];
        i++;
      } else {
        sum += roman[s[i]];
      }
    }
    return sum;
  }
 
  // Driver Code
  public static void Main(String[] args) {
 
    roman['I'] = 1;
    roman['V'] =5;
    roman['X'] =10;
    roman['L'] =50;
    roman['C'] =100;
    roman['D'] =500;
    roman['M'] =1000;
    // Considering inputs given are valid
    String input = "MCMIV";
 
    Console.Write("int form of Roman Numeral is " + romanToInt(input));
  }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// Program to convert Roman
// Numerals to Numbers
 
    var roman = new Map() ;
            roman.set('I', 1);
            roman.set('V', 5);
            roman.set('X', 10);
            roman.set('L', 50);
            roman.set('C', 100);
            roman.set('D', 500);
            roman.set('M', 1000);
     
    // This function returns value
    // of a Roman symbol
     function romanToInt( s) {
        var sum = 0;
        var n = s.length;
 
        for (i = 0; i < n; i++) {
 
            // If present value is less than next value,
            // subtract present from next value and add the
            // resultant to the sum variable.
            if (i != n - 1 && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) {
                sum += roman.get(s.charAt(i + 1)) - roman.get(s.charAt(i));
                i++;
            } else {
                sum += roman.get(s.charAt(i));
            }
        }
        return sum;
    }
 
    // Driver Code
     
        // Considering inputs given are valid
        var input = "MCMIV";
 
        document.write("Integer form of Roman Numeral is " + romanToInt(input));
 
// This code is contributed by Rajput-Ji
</script>


Output

Integer form of Roman Numeral is 1904

Time complexity – O(N)
Auxiliary Space – O(1)

Another Solution: Shorter code using python

C++




#include <iostream>
#include <unordered_map>
 
int romanToInt(std::string s) {
    std::unordered_map<char, int> translations = {
        {'I', 1},
        {'V', 5},
        {'X', 10},
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000}
    };
    int number = 0;
    s = s + ' ';
    for (int i = 0; i < s.size() - 1; i++) {
        if (translations[s[i]] < translations[s[i+1]]) {
            number -= translations[s[i]];
        } else {
            number += translations[s[i]];
        }
    }
    return number;
}
 
int main() {
    std::cout << romanToInt("MCMIV") << std::endl;
    return 0;
}


Java




// Java Program to convert Roman
// Numerals to Numbers
import java.io.*;
import java.util.*;
 
class GFG
{
    public static void romanToInt(String s)
    {
        Map<Character,Integer> translations=new HashMap<Character,Integer>(); 
 
         //Adding elements to map 
        translations.put('I',1); 
        translations.put('V',5); 
        translations.put('X',10); 
        translations.put('L',50); 
        translations.put('C',100); 
        translations.put('D',500); 
        translations.put('M',1000);
       
        s = s.replace("IV","IIII");
        s = s.replace("IX","VIIII");
        s = s.replace("XL","XXXX");
        s = s.replace("XC","LXXXX");
        s = s.replace("CD","CCCC");
        s = s.replace("CM","DCCCC");
          
        int number = 0;
        for (int i = 0; i < s.length(); i++)
        {
            number = number + (translations.get(s.charAt(i)));
        }
        System.out.println(number);
  }
    public static void main (String[] args)
    {
        romanToInt("MCMIV");
    }
}
 
// This code is contributed by kothavvsaakash


C#




// C# Program to convert Roman
// Numerals to Numbers
using System;
using System.Collections.Generic;
 
using System.Collections;
 
public class GFG {
    public static void romanToInt(String s)
    {
        var translations = new Dictionary<char, int>();
        // Adding elements to map
        translations['I'] = 1;
        translations['V'] = 5;
        translations['X'] = 10;
        translations['L'] = 50;
        translations['C'] = 100;
        translations['D'] = 500;
        translations['M'] = 1000;
        s = s.Replace("IV", "IIII");
        s = s.Replace("IX", "VIIII");
        s = s.Replace("XL", "XXXX");
        s = s.Replace("XC", "LXXXX");
        s = s.Replace("CD", "CCCC");
        s = s.Replace("CM", "DCCCC");
        var number = 0;
        for (int i = 0; i < s.Length; i++) {
            number = number + (translations[s[i]]);
        }
        Console.WriteLine(number);
    }
    public static void Main(String[] args)
    {
        romanToInt("MCMIV");
    }
}
 
// This code is contributed by Aarti_Rathi


Python3




def romanToInt(s):
        translations = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }
        number = 0
        s = s.replace("IV", "IIII").replace("IX", "VIIII")
        s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
        s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
        for char in s:
            number += translations[char]
        print(number)
         
romanToInt('MCMIV')


Javascript




<script>
 
function romanToInt(s){
     
    let translations = new Map()
     
    translations.set("I",1)
    translations.set("V",5)
    translations.set("X",10)
    translations.set("L",50)
    translations.set("C",100)
    translations.set("D",500)
    translations.set("M",1000)
 
 
    let number = 0
    s = s.replace("IV", "IIII").replace("IX", "VIIII")
    s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
    s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
    for(let char of s)
        number += translations.get(char)
    document.write(number)
}
         
romanToInt('MCMIV')
 
// code is contributed by shinjanpatra
 
</script>


Output

1904

Time complexity – O(N)
Auxiliary Space – O(1)

Roman to integer using Ladder If-Else approach :

This approach basically follows the fundamental logic of roman numbers, applying the condition in ladder form like if the first character is ‘I’ then the next should be ‘V’ to make it 4 in number else it will be 1.

Implementation of the approach:

C++




// Program to convert Roman
// Numerals to Numbers
#include <bits/stdc++.h>
using namespace std;
 
int romanToDecimal(string s)
{
    // declare two variables first
    // will calculate the number
    // and second will help
    // in iterating through the
    // string character-wise
    int ans = 0, i;
    for (i = 0; i < s.size() - 1; i++) {
        if (s[i] == 'I' && s[i + 1] == 'V') {
            ans += 4;
            i++;
            continue;
        }
        else if (s[i] == 'I' && s[i + 1] == 'X') {
            ans += 9;
            i++;
            continue;
        }
        else if (s[i] == 'X' && s[i + 1] == 'L') {
            ans += 40;
            i++;
            continue;
        }
        else if (s[i] == 'X' && s[i + 1] == 'C') {
            ans += 90;
            i++;
            continue;
        }
        else if (s[i] == 'C' && s[i + 1] == 'D') {
            ans += 400;
            i++;
            continue;
        }
        else if (s[i] == 'C' && s[i + 1] == 'M') {
            ans += 900;
            i++;
            continue;
        }
        // till this we checked all the category like
        // 4,9,40,90 etc.
        else if (s[i] == 'I')
            ans += 1;
        else if (s[i] == 'V')
            ans += 5;
        else if (s[i] == 'X')
            ans += 10;
        else if (s[i] == 'L')
            ans += 50;
        else if (s[i] == 'C')
            ans += 100;
        else if (s[i] == 'D')
            ans += 500;
        else if (s[i] == 'M')
            ans += 1000;
    }
    // for last character that
    // left in the string if last
    // two char comes not in
    // the category of 4,9,40,90 etc
    // as loop is iterating till size-1*/
    if (s.size() > i) {
        if (s[i] == 'I')
            ans += 1;
        else if (s[i] == 'V')
            ans += 5;
        else if (s[i] == 'X')
            ans += 10;
        else if (s[i] == 'L')
            ans += 50;
        else if (s[i] == 'C')
            ans += 100;
        else if (s[i] == 'D')
            ans += 500;
        else if (s[i] == 'M')
            ans += 1000;
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    // Considering inputs given are valid
    string str = "MCMIV";
    cout << "Integer form of Roman Numeral is "
         << romanToDecimal(str) << endl;
 
    return 0;
}


C




// C Program to convert
// Roman number to integer
#include <stdio.h>
#include <string.h>
 
int romanToDecimal(char* s)
{
    // declare two variables first
    // will calculate the number
    // and second will help
    // in iterating through the
    // string character-wise*/
 
    int ans = 0, i;
    for (i = 0; s[i] != '\0'; i++) {
        if (s[i] == 'I' && s[i + 1] == 'V') {
            ans += 4;
            i++;
            continue;
        }
        else if (s[i] == 'I' && s[i + 1] == 'X') {
            ans += 9;
            i++;
            continue;
        }
        else if (s[i] == 'X' && s[i + 1] == 'L') {
            ans += 40;
            i++;
            continue;
        }
        else if (s[i] == 'X' && s[i + 1] == 'C') {
            ans += 90;
            i++;
            continue;
        }
        else if (s[i] == 'C' && s[i + 1] == 'D') {
            ans += 400;
            i++;
            continue;
        }
        else if (s[i] == 'C' && s[i + 1] == 'M') {
            ans += 900;
            i++;
            continue;
        }
        // till this we checked all the category like
        // 4,9,40,90 etc.
        else if (s[i] == 'I')
            ans += 1;
        else if (s[i] == 'V')
            ans += 5;
        else if (s[i] == 'X')
            ans += 10;
        else if (s[i] == 'L')
            ans += 50;
        else if (s[i] == 'C')
            ans += 100;
        else if (s[i] == 'D')
            ans += 500;
        else if (s[i] == 'M')
            ans += 1000;
    }
    // for last character that
    // left in the string if last
    // two char comes not in the
    // category of 4,9,40,90 etc
    // as loop is iterating till size-1*/
    if (s[i] != '\0') {
        if (s[i] == 'I')
            ans += 1;
        else if (s[i] == 'V')
            ans += 5;
        else if (s[i] == 'X')
            ans += 10;
        else if (s[i] == 'L')
            ans += 50;
        else if (s[i] == 'C')
            ans += 100;
        else if (s[i] == 'D')
            ans += 500;
        else if (s[i] == 'M')
            ans += 1000;
    }
 
    return ans;
}
 
int main()
{
    // Considering inputs given are valid
    char str[] = "MCMIV";
    printf("Integer form of Roman Numeral is %d\n",
           romanToDecimal(str));
 
    return 0;
}


Python3




def romanToDecimal(s: str) -> int:
    # declare two variables first
    # will calculate the number
    # and second will help
    # in iterating through the
    # string character-wise
    ans = 0
    i = 0
    while i < len(s) - 1:
        if s[i] == 'I' and s[i + 1] == 'V':
            ans += 4
            i += 2
        elif s[i] == 'I' and s[i + 1] == 'X':
            ans += 9
            i += 2
        elif s[i] == 'X' and s[i + 1] == 'L':
            ans += 40
            i += 2
        elif s[i] == 'X' and s[i + 1] == 'C':
            ans += 90
            i += 2
        elif s[i] == 'C' and s[i + 1] == 'D':
            ans += 400
            i += 2
        elif s[i] == 'C' and s[i + 1] == 'M':
            ans += 900
            i += 2
        # till this we checked all the category like
        # 4,9,40,90 etc.
        else:
            if s[i] == 'I':
                ans += 1
            elif s[i] == 'V':
                ans += 5
            elif s[i] == 'X':
                ans += 10
            elif s[i] == 'L':
                ans += 50
            elif s[i] == 'C':
                ans += 100
            elif s[i] == 'D':
                ans += 500
            elif s[i] == 'M':
                ans += 1000
            i += 1
 
    # for last character that
    # left in the string if last
    # two char comes not in
    # the category of 4,9,40,90 etc
    # as loop is iterating till size-1
    if i < len(s):
        if s[i] == 'I':
            ans += 1
        elif s[i] == 'V':
            ans += 5
        elif s[i] == 'X':
            ans += 10
        elif s[i] == 'L':
            ans += 50
        elif s[i] == 'C':
            ans += 100
        elif s[i] == 'D':
            ans += 500
        elif s[i] == 'M':
            ans += 1000
 
    return ans
 
# Driver Code
if __name__ == "__main__":
    # Considering inputs given are valid
    str = "MCMIV"
    print("Integer form of Roman Numeral is", romanToDecimal(str))


C#




// C# code addition
using System;
 
class Program
{
 
  static int RomanToDecimal(string s)
  {
 
    // declare two variables first
    // will calculate the number
    // and second will help
    // in iterating through the
    // string character-wise*/
    int ans = 0;
    for (int i = 0; i < s.Length - 1; i++)
    {
      if (s[i] == 'I' && s[i + 1] == 'V')
      {
        ans += -1;
        i++;
        continue;
      }
      else if (s[i] == 'I' && s[i + 1] == 'X')
      {
        ans += 9;
        i++;
        continue;
      }
      else if (s[i] == 'X' && s[i + 1] == 'L')
      {
        ans += 40;
        i++;
        continue;
      }
      else if (s[i] == 'X' && s[i + 1] == 'C')
      {
        ans += 90;
        i++;
        continue;
      }
      else if (s[i] == 'C' && s[i + 1] == 'D')
      {
        ans += 400;
        i++;
        continue;
      }
      else if (s[i] == 'C' && s[i + 1] == 'M')
      {
        ans += 900;
        i++;
        continue;
      }
 
      // till this we checked all the category like
      // 4,9,40,90 etc.
      else if (s[i] == 'I')
        ans += 1;
      else if (s[i] == 'V')
        ans += 5;
      else if (s[i] == 'X')
        ans += 10;
      else if (s[i] == 'L')
        ans += 50;
      else if (s[i] == 'C')
        ans += 100;
      else if (s[i] == 'D')
        ans += 500;
      else if (s[i] == 'M')
        ans += 1000;
    }
 
    // for last character that
    // left in the string if last
    // two char comes not in
    // the category of 4,9,40,90 etc
    // as loop is iterating till size-1
    if (s.Length > 0)
    {
      int lastCharIndex = s.Length - 1;
      if (s[lastCharIndex] == 'I')
        ans += 1;
      else if (s[lastCharIndex] == 'V')
        ans += 5;
      else if (s[lastCharIndex] == 'X')
        ans += 10;
      else if (s[lastCharIndex] == 'L')
        ans += 50;
      else if (s[lastCharIndex] == 'C')
        ans += 100;
      else if (s[lastCharIndex] == 'D')
        ans += 500;
      else if (s[lastCharIndex] == 'M')
        ans += 1000;
    }
    return ans;
  }
 
  static void Main(string[] args)
  {
    // Considering inputs given are valid
    string str = "MCMIV";
    Console.WriteLine("Integer form of Roman Numeral is {0}", RomanToDecimal(str));
  }
}
 
// The code is contributed by Nidhi goel.


Javascript




// Program to convert Roman
// Numerals to Numbers
function romanToDecimal(s)
{
 
    // declare two variables first
    // will calculate the number
    // and second will help
    // in iterating through the
    // string character-wise
    let ans = 0, i=0;
    for (i = 0; i < s.length - 1; i++) {
        if (s[i] === 'I' && s[i + 1] === 'V') {
            ans += 4;
            i++;
            continue;
        }
        else if (s[i] === 'I' && s[i + 1] === 'X') {
            ans += 9;
            i++;
            continue;
        }
        else if (s[i] === 'X' && s[i + 1] === 'L') {
            ans += 40;
            i++;
            continue;
        }
        else if (s[i] === 'X' && s[i + 1] === 'C') {
            ans += 90;
            i++;
            continue;
        }
        else if (s[i] === 'C' && s[i + 1] === 'D') {
            ans += 400;
            i++;
            continue;
        }
        else if (s[i] === 'C' && s[i + 1] === 'M') {
            ans += 900;
            i++;
            continue;
        }
         
        // till this we checked all the category like
        // 4,9,40,90 etc.
        else if (s[i] === 'I') ans += 1;
        else if (s[i] === 'V') ans += 5;
        else if (s[i] === 'X') ans += 10;
        else if (s[i] === 'L') ans += 50;
        else if (s[i] === 'C') ans += 100;
        else if (s[i] === 'D') ans += 500;
        else if (s[i] === 'M') ans += 1000;
    }
     
    // for last character that
    // left in the string if last
    // two char comes not in
    // the category of 4,9,40,90 etc
    // as loop is iterating till size-1*/
    if (s.length > i) {
        if (s[i] === 'I') ans += 1;
        else if (s[i] === 'V') ans += 5;
        else if (s[i] === 'X') ans += 10;
        else if (s[i] === 'L') ans += 50;
        else if (s[i] === 'C') ans += 100;
        else if (s[i] === 'D') ans += 500;
        else if (s[i] === 'M') ans += 1000;
    }
 
    return ans;
}
 
// Considering inputs given are valid
let str = "MCMIV";
console.log("Integer form of Roman Numeral is " + romanToDecimal(str));


Java




import java.util.*;
 
public class RomanToDecimal {
    public static int romanToDecimal(String s) {
        // Declare a map to store the values of Roman numerals
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
 
        int ans = 0;
        // Iterate through the string character-wise
        for (int i = 0; i < s.length(); i++) {
            // If the current character is smaller than the next character, subtract its value from the answer
            if (i < s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
                ans -= map.get(s.charAt(i));
            }
            // Else, add its value to the answer
            else {
                ans += map.get(s.charAt(i));
            }
        }
        return ans;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Considering inputs given are valid
        String str = "MCMIV";
        System.out.println("Integer form of Roman Numeral is " + romanToDecimal(str));
    }
}


Output

Integer form of Roman Numeral is 1904

Time complexity – O(N)
Auxiliary Space – O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments