# State Machine C++ Solution

• String table is copied from a neat solution of IntegerToRoman
Easy to find the state changing pattern.
Here's my code FYI

``````class Solution {
public:
int romanToInt(string s) {
const string M[] = {"", "M", "MM", "MMM"};
const string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
const string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
const string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
int res = 0,i=0,state = 0;
string s1,s2,s3;
while(i<s.size()){
switch(state){
case 0:
if(s[i]=='C'||s[i]=='D')
state = 1;
else if(s[i]=='X'||s[i]=='L')
state = 2;
else if(s[i]=='I'||s[i]=='V')
state = 3;
else{
res+=1000;
i++;
}
break;
case 1:
if(s[i]=='X'||s[i]=='L')
state = 2;
else if(s[i]=='I'||s[i]=='V')
state = 3;
else{
s1 += s[i++];
}
break;
case 2:
if(s[i]=='I'||s[i]=='V')
state = 3;
else{
s2 += s[i++];
}
break;
case 3:
s3 = s.substr(i);
i = s.size();
break;
}
}

for (int i=0;i<10;++i){
res += (C[i]==s1?100*i:0)
+(X[i]==s2?10*i:0)
+(I[i]==s3?i:0);
}
return res;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.