# C# Solution

• One way is using switch. The other way use dictionary and calculate from string end to string beginning.

public int RomanToInt(string s) {
//Symbol I V X L C D M
//Value 1 5 10 50 100 500 1000
if(s.Length==0) return 0;

``````    int sum, current,pre;
sum=Transfer2Int(s[0]); //sum original values the first number
for(int i=1; i<s.Length;i++)
{
pre=Transfer2Int(s[i-1]);
current=Transfer2Int(s[i]);
if(pre<current)
{
sum=sum-2*pre+current;
}
else
{
sum=sum+current;
}
}

return sum;
}

public int Transfer2Int(char c)
{
int num=0;
switch(c)
{
case 'I': num=1;
break;
case 'V': num=5;
break;
case 'X': num=10;
break;
case 'L': num=50;
break;
case 'C': num=100;
break;
case 'D': num=500;
break;
case 'M': num=1000;
break;

}
return num;
}
``````

public int RomanToInt(string s) {
if(s.Length==0) return 0;
Dictionary<char,int> dic= new Dictionary<char, int>
{
{'I', 1},
{'V', 5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};

``````    int sum=dic[s[(s.Length-1)]];

for(int i=s.Length-2; i>=0; i--)
{
if(dic[s[i]]<dic[s[i+1]])
{
sum=sum-dic[s[i]];
}
else
{
sum=sum+dic[s[i]];
}
}

return sum;
``````

}

• ''''
public class Solution {

``````public int RomanToInt(string str)
{
int sum = 0;
char[] chrArr = str.ToCharArray();

for(int i = 0; i < chrArr.Length; i++)
{
if (i == 0 && chrArr[i] == 'M')
{
sum = ConvertRomanToInt(chrArr[i]);
}
else if (i + 1 < chrArr.Length && ConvertRomanToInt(chrArr[i]) < ConvertRomanToInt(chrArr[i+1]))
{
sum += ConvertRomanToInt(chrArr[i + 1]) - ConvertRomanToInt(chrArr[i]);
i++;
}
else
{
sum += ConvertRomanToInt(chrArr[i]);
}
}

return sum;
}

public int ConvertRomanToInt(char chr)
{

int result = 0;

switch (chr)
{

case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
break;

}

return result;
}
``````

}
''''

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