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 cnt = 0;
int n = s.size();
for(int i = 0; i < n - 1; i++)
{
if(tonumber(s[i]) < tonumber(s[i+1]))
cnt -= tonumber(s[i]);
else
cnt += tonumber(s[i]);
}
cnt += tonumber(s[n - 1]);
return cnt;
}
int tonumber(char ch)
{
switch(ch)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
return 0;
}
};
better answer map的用法 写的太精巧。,
int romanToInt(string s) {
static unordered_map<char, int> ROMAN = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000},};
int value = 0;
for (int i = 0; i < s.size(); i++) value += ((i < s.size() - 1 && ROMAN[s[i+1]] > ROMAN[s[i]]) ? -ROMAN[s[i]] : ROMAN[s[i]]);
return value;
}