Leetcode, RomanToInteger
#include <iostream>
#include <string>
using namespace std;
int map(const char c)
{
switch (c)
{
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;
}
}
//时间复杂度O(n),空间复杂度O(1)
int solution(string s)
{
int result = 0;
for ( size_t i = 0; i < s.size(); ++i )
{
#if 0
{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
{ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
4 IV = I + V - 2 * I
9 IX = I + X - 2 * I
40 XL = X + L - 2 * L
90 XC = X + C - 2 * C
...
#endif // 0
if ( i > 0 && map(s[i]) > map(s[i - 1]) )
{
result += (map(s[i]) - 2 * map(s[i - 1]) );
}
else
{
result += map(s[i]);
}
}
return result;
}
int main()
{
cout << solution("III") << endl; //3
cout << solution("IV") << endl; //4
cout << solution("IX") << endl; //9
cout << solution("LVIII") << endl; //58
cout << solution("MCMXCIV") << endl;//1994
return 0;
}