[Leetcode] Roman to Integer

Given a roman numeral, convert it to an integer.

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

纯模拟,规则见:Integer to Roman

 1 class Solution {
 2 public:
 3     map<char, int> roman;
 4     void init() {
 5         roman['I'] = 1;
 6         roman['V'] = 5;
 7         roman['X'] = 10;
 8         roman['L'] = 50;
 9         roman['C'] = 100;
10         roman['D'] = 500;
11         roman['M'] = 1000;
12     }
13     
14     bool check(char a, char b) {
15         return roman[a] < roman[b];
16     }
17     
18     int romanToInt(string s) {
19         init();
20         int res = 0;
21         for (int i = 0; i < s.length(); ++i) {
22             if (i > 0 && check(s[i-1], s[i])) {
23                 res -= 2 * roman[s[i-1]];
24             }
25             res += roman[s[i]];
26         }
27         return res;
28     }
29 };

 

posted @ 2014-04-10 17:18  Eason Liu  阅读(147)  评论(0编辑  收藏  举报