The Wayback Machine - https://web.archive.org/web/20240814153327/https://www.geeksforgeeks.org/cpp-program-for-converting-roman-numerals-to-decimal-lying-between-1-to-3999/
Open In App

C++ Program For Converting Roman Numerals To Decimal Lying Between 1 to 3999

Last Updated : 29 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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




// 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;
}


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




// 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;
}


Output:

Integer form of Roman Numeral is 1904

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

Please refer complete article on

Converting Roman Numerals to Decimal lying between 1 to 3999

for more details!



Similar Reads

Javascript Program For Converting Roman Numerals To Decimal Lying Between 1 to 3999
Given a Romal 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 fourRecommended: Please solve it on "PRACTICE" first, before moving on
3 min read
Converting Decimal Number lying between 1 to 3999 to Roman Numerals
Given a number, find its corresponding Roman numeral. Examples: Input : 9Output : IXInput : 40Output : XLInput : 1904Output : MCMIVFollowing is the list of Roman symbols which include subtractive cases also: SYMBOL VALUEI 1IV 4V 5IX 9X 10XL 40L 50XC 90C 100CD 400D 500CM 900 M 1000 Idea is to convert the units, tens, hundreds, and thousands of place
15+ min read
Converting Roman Numerals to Integer
Given a string in roman form, the task is to convert this given roman string into an integer. Roman numerals are based on the following symbols: Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Example: Input: IXOutput: 9Explanation: IX is a Roman symbol which represents 9 Input: XLOutput: 40Explanation: XL is a Roman symbol which represents 40 In
10 min read
Sort an array of Roman Numerals in ascending order
Given an array arr[] of N Roman Numerals, the task is to sort these Roman Numerals in ascending order. Examples: Input: arr[] = { "MCMIV", "MIV", "MCM", "MMIV" } Output: MIV MCM MCMIV MMIV Explanation: The roman numerals in their corresponding decimal system are: MIV: 1004 MCM: 1900 MCMIV: 1904 MMIV: 2004 Input: arr = { "MV", "MIV", "MCM", "MM" } O
12 min read
Pair having all other given pairs lying between its minimum and maximum
Given a 2D array arr[][] consisting of N pairs of integers, the task is to find the pair which covers all other pairs of the given array. If it is impossible to find such a pair, then print -1. A pair {a, ?b} will cover another pair {c, ?d}, if the condition (a???c???d???b) holds true. Examples: Input: arr[][2] = {{2, 2}, {3, 3}, {3, 5}, {4, 5}, {1
12 min read
Convert Decimal To Hexa-Decimal including negative numbers
Given a number N in decimal format, the task is to convert it to the hexadecimal representation of N as a string. Negative numbers are stored in 2's complement form. Examples: Input: N = 134 Output: 86Explanation: 134 = 00000000000000000000000010001000 in 32 bit representation. Grouping in four-size chunks and converting each chunk to equivalent he
14 min read
Sum of all Perfect Squares lying in the range [L, R] for Q queries
Given Q queries in the form of 2D array arr[][] whose every row consists of two numbers L and R which signifies the range [L, R], the task is to find the sum of all perfect squares lying in this range. Examples: Input: Q = 2, arr[][] = {{4, 9}, {4, 16}} Output: 13 29 Explanation: From 4 to 9: only 4 and 9 are perfect squares. Therefore, 4 + 9 = 13.
7 min read
Sum of all Perfect Cubes lying in the range [L, R] for Q queries
Given Q queries in the form of 2D array arr[][] whose every row consists of two numbers L and R which signifies the range [L, R], the task is to find the sum of all perfect cubes lying in this range.Examples: Input: Q = 2, arr[][] = {{4, 9}, {4, 44}} Output: 8 35 From 4 to 9: only 8 is the perfect cube. Therefore, 8 is the ans From 4 to 44: 8, and
7 min read
Sum of all palindromic numbers lying in the range [L, R] for Q queries
Given Q queries in the form of 2D array arr[][] whose every row consists of two numbers L and R which denotes the range [L, R], the task is to find the sum of all Palindrome Numbers lying in range [L, R]. Input: Q = 2, arr[][] = { {10, 13}, {12, 21} } Output: 11 0 Explanation: From 10 to 13 only 11 is the palindrome number From 12 to 21 there is no
8 min read
Sum of all armstrong numbers lying in the range [L, R] for Q queries
Given Q queries in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes a range [L, R], the task is to find the sum of all Armstrong Numbers lying in the given range [L, R].Examples: Input: Q = 2, arr = [ [1, 13], [121, 211] ] Output: 45 153 Explanation: From 1 to 13, 1, 2, 3, 4, 5, 6, 7, 8 and 9 are the A
9 min read
three90RightbarBannerImg