Simplest Solution after understanding how Roman Numerals Works


#1

If any roman numeral having less value comes before numeral having value we have to add diff of both otherwise add actual value

int Solution::romanToInt(string A) {
unordered_map<char,int> roman;
roman[‘I’]=1;
roman[‘V’]=5;
roman[‘X’]=10;
roman[‘L’]=50;
roman[‘C’]=100;
roman[‘D’]=500;
roman[‘M’]=1000;
int sum=0;
for(int i=0;i<A.length();i++)
{
if(roman[A[i]]<roman[A[i+1]])
{
sum=sum+(roman[A[i+1]]-roman[A[i]]);
i++;
continue;
}
else
{
sum=sum+roman[A[i]];
}
}
return sum;
}


#2

your code fails for A=IIV that’s because you didn’t consider the condn if A[i]==A[i+1]; this case count no. of repeated characters and if the next char(i.e char after repeated chars) is greater then you subtract the value of repeated chars otherwise keep adding them as you do for( A[i+1]<A[i]);
for IIV count of repeated chars (i.e ‘I’)is 2 and after that you get bigger value(i.e V=5)therefore you subtract 2 from 5 and add to the answer, which in this case is -2+5=3;
Thank you.