Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
给定一个罗马数字将之转化为整数、
利用dictionary建立各个单罗马字母与数字对应的关系,并通过对比罗马字母之后的罗马字母来判断加还是减。
public class Solution {
public int RomanToInt(string s) {
Dictionary<char,int> map = new Dictionary<char,int>();
map.Add('I', 1);
map.Add('V', 5);
map.Add('X', 10);
map.Add('L', 50);
map.Add('C', 100);
map.Add('D', 500);
map.Add('M', 1000);
int sum = 0;
for(int i = 0;i<s.Length;i++){
sum += RomanToInt2(s, i, map) * map[s[i]];
}
return sum;
}
public static int RomanToInt2(string s,int i,Dictionary<char,int> map){
if(i == s.Length -1) return 1;
else if(map[s[i]] < map[s[i + 1]]){
return -1;
}
else{
return 1;
}
}
}