LeetCode: Roman to Integer
13. Roman to Integer
Total Accepted: 77116 Total Submissions: 199727 Difficulty: Easy
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution { public: int romanToInt(string s) { int map[26]; char romanChar[] = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' }; map['I' - 'A'] = 1; map['V' - 'A'] = 5; map['X' - 'A'] = 10; map['L' - 'A'] = 50; map['C' - 'A'] = 100; map['D' - 'A'] = 500; map['M' - 'A'] = 1000; int res = 0, tmp = 0; for (int i = 0; i < s.size(); i++) { if (map[s[i] - 'A'] > tmp) { res = res + map[s[i] - 'A'] - tmp * 2; } else { res = res + map[s[i] - 'A']; } tmp = map[s[i] - 'A']; } return res; } };