Roman to Integer [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.


 

Traverse given string, if next roman value is smaller than the previous one, just add it to result.

If next roman value is larger than previous one, we need to do a minus.

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         std::map<char, int> roman_value_map;
 6         roman_value_map.insert( pair<char, int>('M', 1000));
 7         roman_value_map.insert( pair<char, int>('D', 500));
 8         roman_value_map.insert( pair<char, int>('C', 100));
 9         roman_value_map.insert( pair<char, int>('L', 50));
10         roman_value_map.insert( pair<char, int>('X', 10));
11         roman_value_map.insert( pair<char, int>('V', 5));
12         roman_value_map.insert( pair<char, int>('I', 1));
13         
14         std::map<char, int>::iterator iter;
15         int result = 0;
16         int cur_value = 0;
17         for (int i = 0 ; i < s.size(); i++) {
18             iter = roman_value_map.find(s[i]);
19             if(0 == cur_value or cur_value >= iter->second) {
20                 cur_value = iter->second;
21                 result += cur_value;
22             } else {
23                 result -= cur_value;
24                 cur_value = iter->second - cur_value;
25                 result += cur_value;
26             }
27         }
28         return result;
29 
30     }
31 };

 

posted @ 2013-10-23 11:30  昱铭  阅读(192)  评论(0)    收藏  举报