Super easy c++ solution based on how roman numerals work


#1

We traverse the string from right, if we counter a roman char smaller in value we subtract its value from ans else add.
int Solution::romanToInt(string A) {
if(A.length()==0) return 0;
int n=A.length();
vector roman(256);
roman[‘I’]=1;
roman[‘V’]=5;
roman[‘X’]=10;
roman[‘L’]=50;
roman[‘C’]=100;
roman[‘D’]=500;
roman[‘M’]=1000;
int ans=roman[A[n-1]];
for(int i=n-2;i>=0;i–){
if(roman[A[i]]<roman[A[i+1]]){
ans-=roman[A[i]];
}
else{
ans+=roman[A[i]];
}

}
return ans;

}