LeetCode Online Judge 题目C# 练习 - Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 1         public static int RomantoInteger2(string s)
 2         {
 3             Dictionary<char, int> map = new Dictionary<char, int>();
 4             map.Add('I', 1);
 5             map.Add('V', 5);
 6             map.Add('X', 10);
 7             map.Add('L', 50);
 8             map.Add('C', 100);
 9             map.Add('D', 500);
10             map.Add('M', 1000);
11 
12             int x = 0;
13             for (int i = 0; i < s.Length; i++)
14             {
15                 x += RomantoInteger2Sign(s, i, map) * map[s[i]];
16             }
17 
18             return x;
19         }
20 
21         public static int RomantoInteger2Sign(string s, int i, Dictionary<char, int> map)
22         {
23             if (i == s.Length - 1)
24                 return 1;
25             else if (map[s[i]] < map[s[i + 1]])
26                 return -1;
27             else
28                 return 1;
29         }

代码分析:

  抄来之码, 第一次写的另外一个做法,把,1~9, 10~90, 100~900,1000做了一个look up table,然后分别把one, ten, hundred, thousand,位独立开,然后再look up table中找出,乘以相应的倍数 += 到 ret 中。Look up table 对于 Integer to Roman 是非常方便的,但是在Roman to Integer中反而有点罗嗦。 所以抄来上面的代码。

  观察到只有 4 和 9 做减法 (4 = IV = 5 - 1, 9 = IX = 10 - 1), 所以有了上面RomantoInteger2Sign 函数。

  例如 “CDLXIV” = -100 + 500 + 50 + 10 - 1 +5 = 464