Convert Roman Number Into Integer using STL in C++

Hello Friends, Today we are going to learn how to convert roman number into integer in C++ using STL. This problem you can do also using the stack as well as using STL. I will give you the link below so that you can see how to do this problem using stack also.

Here I will teach you how to do using STL. Let’s start with roman representation first then an example for understanding the question and later on we will see the algorithm as well as code.

I -1 , V- 5 , X- 10 , L – 50 , C – 100, D – 500, M – 1000

EXAMPLE :

Input: LI

Here L represents 50 where I represents 1. So, the decimal value will be 51.
Output: 51

C++ code for Roman Into Integer using STL

Here, Input should be a string and output should be a decimal value.
Time Complexity = O(S) where S = length of string

#include <bits/stdc++.h>
using namespace std;
int roman_decimal(string &str);  

int main() 
{
        string s;     // Suppose input is XL
        cin >> s;
        cout << roman_decimal(s) << endl; 
}

int roman_decimal(string &str)
{
   unordered_map<char,int> m;
   m['I'] = 1;
   m['V'] = 5;
   m['X'] = 10;
   m['L'] = 50;
   m['C'] = 100;
   m['D'] = 500;
   m['M'] = 1000;
   
   int answer = 0;
    for(int i=0;i<str.length();i++)
    {
        if(i+1<str.length() && m[str[i]]< m[str[i+1]])
        {
            answer += m[str[i+1]]- m[str[i]];
            i++;
        }
       else
       {
          answer += m[str[i]];
       }
    }
   return answer;
}
Output : 40

Understanding the Algorithm

The algorithm is quite simple. Suppose Input is LX , so output will be (L= 50)+(X=10) = 60. But when input is XL, the output will be 50-10 = 40. But here the question arises, when we will add or when we will subtract.

Now, start from the Left-hand side and move towards the right-hand side one by one, we will add when the next number is less than the current index number like in example ‘XL’. Here, Value of L(which is 50)> Value of X(which is 10). So, we will subtract the next index number from the current index. Otherwise, we will keep adding.

This condition will take care of above problem ——    (i+1<str.length() && m[str[i]]< m[str[i+1]] ).
And the rest of the things is easy only. I created an unordered map for storing the value of the alphabet and created one variable in which we are storing the answer.

You can check out this article also and understand how to do using stack also.

Conversion of roman numerals to decimal in C++

 

Leave a Reply

Your email address will not be published. Required fields are marked *