13. Roman to Integer
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: s = "III"
Output: 3Last updated
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: s = "III"
Output: 3Last updated
Input: s = "IV"
Output: 4Input: s = "IX"
Output: 9Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.public class Solution {
public int RomanToInt(string s) {
int total = 0;
char[] Roman = s.ToCharArray();
Dictionary<char, int> dict = new Dictionary<char, int>();
dict.Add('I', 1);
dict.Add('V', 5);
dict.Add('X', 10);
dict.Add('L', 50);
dict.Add('C', 100);
dict.Add('D', 500);
dict.Add('M', 1000);
for(int i = 0; i < Roman.Length; i++){
total += dict[Roman[i]];
if(Roman[i] == 'I' && i + 1 < Roman.Length){
if(Roman[i + 1] == 'V' || Roman[i + 1] == 'X'){
total -= 2;
}
}
if(Roman[i] == 'X' && i + 1 < Roman.Length){
if(Roman[i + 1] == 'L' || Roman[i + 1] == 'C'){
total -= 20;
}
}
if(Roman[i] == 'C' && i + 1 < Roman.Length){
if(Roman[i + 1] == 'D' || Roman[i + 1] == 'M'){
total -= 200;
}
}
}
return total;
}
}