/**
* Given a roman numeral, convert it to an integer.
* Input is guaranteed to be within the range from 1 to 3999.
*/
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
//MMMCMXCIX
int romanToInt(string s)
{
unordered_map<char, int> map = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, {'M', 1000} };
int sum = map[s.back()];
for (int i = s.length() - 2; i >= 0; i--)
{
if (map[s[i]] < map[s[i+1]])
{
sum -= map[s[i]];
}
else
{
sum += map[s[i]];
}
}
return sum;
}
int main()
{
cout << romanToInt(string("MMMCMXCIX"));
system("pause");
return 0;
}
【leetcode】13. Roman to Integer
最新推荐文章于 2023-10-30 12:20:17 发布