0013 Roman To Integer
问题概述
解题思路
class Solution
{
public:
int romanToInt(std::string s)
{
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
if (i + 1 < s.length() && GetValue(s[i]) < GetValue(s[i + 1]))
{
sum += GetValue(s[i + 1]) - GetValue(s[i]);
i++;
}
else
{
sum += GetValue(s[i]);
}
}
return sum;
}
private:
int GetValue(char ch)
{
int value = 0;
switch (ch)
{
case 'I': value = 1; break;
case 'V': value = 5; break;
case 'X': value = 10; break;
case 'L': value = 50; break;
case 'C': value = 100; break;
case 'D': value = 500; break;
case 'M': value = 1000; break;
default:
break;
}
return value;
}
};
class Solution
{
public:
std::map<char, int> RomanIntMap = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
int romanToInt(std::string s)
{
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
if (i + 1 < s.length() && RomanIntMap[s[i]] < RomanIntMap[s[i + 1]])
{
sum += RomanIntMap[s[i + 1]] - RomanIntMap[s[i]];
i++;
}
else
{
sum += RomanIntMap[s[i]];
}
}
return sum;
}
};