题解:
善于用STL的map容器,具体看代码。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
/*
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
*/
int romanToInt(string s)
{
// 存放普通情况和特殊情况(也就是小的在左边的6种情况)的map
map <string,int> mp;
// 7种普通的情况
mp["I"] = 1; mp["V"] = 5;
mp["X"] = 10;mp["L"] = 50;
mp["C"] = 100;mp["D"] = 500; mp["M"] = 1000;
// 6种特殊的情况
mp["IV"] = 4; mp["IX"] = 9;
mp["XL"] = 40; mp["XC"] = 90;
mp["CD"] = 400; mp["CM"] = 900;
int sum = 0;
for(int i = 0; i < (int)s.length(); )
{
// 1.先判断是否第i个字符是否能和后面的形成特殊的情况
string tmp = "";
tmp += s[i];
if(i != ((int)s.length()-1))
{
tmp += s[i+1];
}
if(mp[tmp] != 0)
{
sum += mp[tmp];
i += 2;
continue;
}
// 2.如果不是特殊情况,再按正常的求
tmp = "";
tmp += s[i];
sum += mp[tmp];
i++;
}
return sum;
}
int main()
{
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
string roman;
while(cin >> roman)
{
cout << romanToInt(roman) << endl;
}
return 0;
}