Roman Number to Integer | Practice | GeeksforGeeks

Given a string in roman no format (s)  your task is to convert it to an integer . Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input:
s = V
Output: 5

Example 2:
Input:
s = III 
Output: 3

Your Task:
Complete the function romanToDecimal() which takes a string as input parameter and returns the equivalent decimal number. 
Expected Time Complexity: O(|S|), |S| = length of string S.
Expected Auxiliary Space: O(1)
Constraints:
1<=roman no range<=3999
 
0
preethirakasi4 days ago
Can someone say what's wrong with this code, its failing for this i/p:-"CMXVI" , my program o/p here after submiting is 916, expected is 1116. When i run this outside on any othersite its giving me correct o/p for the above i/p
 
public int romanToDecimal(String str) {       // code here       HashMap<String,Integer> RomanValuesMap=new HashMap<String,Integer>();       RomanValuesMap.put("I",1);       RomanValuesMap.put("V",5);       RomanValuesMap.put("X",10);       RomanValuesMap.put("L",50);       RomanValuesMap.put("C",100);       RomanValuesMap.put("D",500);       RomanValuesMap.put("M",1000);       int count=0;       for(int i=0;i<str.length();i++){           char ch=str.charAt(i);           String s=Character.toString(ch);           if(RomanValuesMap.containsKey(s)){               count+=RomanValuesMap.get(s);           }       }       return count;   }
0
chandumarghade6 days ago
Code For JAVA

class Solution {
    // Finds decimal value of a given roman numeral
    public int romanToDecimal(String str) {
        int sum=0;
        for(int i=0;i<str.length()-1;i++){
            int  a =value(str.charAt(i));
            int  b =value(str.charAt(i+1));
            if(a>=b){
                sum=sum+value(str.charAt(i));
            }
            else {
                sum=sum-value(str.charAt(i));
            }
        }
        
        sum=sum+value(str.charAt(str.length()-1));
        return sum;
        // code here
    }
    public int value(char s){
        if(s=='I'){
            return 1;
        }
        else if(s=='V'){
            return 5;
        }
        else if(s=='X'){
            return 10;
        }
        else if(s=='L'){
            return 50;
        }
        else if(s=='C'){
            return 100;
        }
        else if(s=='D'){
            return 500;
        }
        else if(s=='M'){
            return 1000;
        }
        return -1;
    }
}
+2
darkvoid65656 days ago
EASY TO READ SOLUTION-→
Runtime = 0.01 sec
idea is to store the value of roman numbers in an unordered map, and iterate over the string if char at i> i+1,then add, otherwise subtract it from the ans, it is the rule of writing roman numbers.
class Solution { public:   int romanToDecimal(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 n=str.length();   int ans=0;   for (int i = 0; i < n; i++)   {if (m[str[i]]>=m[str[i+1]])       {                  ans+=m[str[i]];       }       else{           ans-=m[str[i]];       }    }   return ans;   }};upvote if you understand
0
velspace011 week ago
Java sol
public int romanToDecimal(String str) {
        HashMap<String,Integer> hm=new HashMap<>();
        hm.put("M",1000);
        hm.put("CM",900);
        hm.put("D",500);
        hm.put("CD",400);
        hm.put("C",100);
        hm.put("XC",90);
        hm.put("L",50);
        hm.put("XL",40);
        hm.put("X",10);
        hm.put("IX",9);
        hm.put("V",5);
        hm.put("IV",4);
        hm.put("I",1);
        int sum=0;
        for(int i=0;i<str.length();i++){
            String s=" ";
            if(i<str.length()-1){
             s=str.substring(i,i+2);
            }
            if(hm.containsKey(s)){
                sum+=hm.get(s);
                i++;
            }else{
                sum+=hm.get(str.substring(i,i+1));
            }
        }
        return sum;
    }
+1
badgujarsachin831 week ago
 int romanToDecimal(string &str) {
        // code here
        map<char,int> mp={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
        int val=0;
        int pre=INT_MAX;
        for(int i=0;i<str.size();i++){
            if(mp[str[i]]>=mp[str[i+1]]){
                val+=mp[str[i]];
            }else{
                val-=mp[str[i]];
            }
        }
        return val;
    }
-1
tapanmanu20002 weeks ago
0.01 sec runtime
int romanToDecimal(string &str) {
        map<char,int> romans = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},
                                        {'D',500},{'M',1000}};
        int val = 0;
        int prev = INT_MAX;
        for(auto ch:str){
            if(romans.find(ch) != romans.end()){
                if(romans[ch] > prev){
                    val -= 2 * prev;
                }
                val += romans[ch];
            }
            prev = romans[ch];
        }
        return val;
    }
+2
anandgeeky2 weeks ago
JAVA CODE:
 
class Solution {   // Finds decimal value of a given roman numeral   public int romanToDecimal(String str) {       // code here       int result = convertRomanToInteger(str.charAt(0));              for(int i = 1; i < str.length(); i++) {           int pre = convertRomanToInteger(str.charAt(i - 1));           int curr = convertRomanToInteger(str.charAt(i));                      if(pre >= curr)               result += curr;            else               result = result - pre + curr - pre;        }        return result;   }        private int convertRomanToInteger(char roman) {       switch(roman) {           case 'I':                return 1;           case 'V':               return 5;           case 'X':                return 10;           case 'L':                return 50;           case 'C':                return 100;           case 'D':                return 500;           case 'M':               return 1000;       }       return 0;   }}
-1
mdnafishalam542 weeks ago
 int romanToDecimal(string &str) {       // code here       map<char,int> val={  {'I',1},{'V',5},{'X',10},{'L',50},                          {'C',100},{'D',500},{'M',1000}                          };       int decimal=0;       for(int i=0;i<str.size();i++){           // If the current value is greater than or equal            // to the value of the symbol to the right           if(val[str[i]]>=val[str[i+1]]) decimal+=val[str[i]];            // If the current value is smaller than             // the value of the symbol to the right           else decimal-=val[str[i]];       }       return decimal;          }
+1
lokeshchoubisa263 weeks ago
 int romanToDecimal(string &str) {       // code here       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 n=str.size();       char ch=str[n-1];       int sum=m[ch];       int prev=sum;       for(int i=str.size()-2;i>=0;i--)       {           char ch=str[i];           if(m[ch]>=prev)           {               sum+=m[ch];           }           else           {               sum-=m[ch];           }           prev=m[ch];       }                     return sum;   }
0
imohdalam3 weeks ago
JAVA | O(n)
class Solution {
    // Finds decimal value of a given roman numeral
    public int romanToDecimal(String str) {
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        
            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 result = 0;
        int n = str.length();
        
        for(int i=0; i<n-1; i++){
            char curr = str.charAt(i);
            char next = str.charAt(i + 1);
            if(map.get(curr) < map.get(next))
              result -= map.get(curr);
            else
               result += map.get(curr);
        }
        
        result += map.get(str.charAt(n - 1));
        
        return result;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.