题目: 传送门
将罗马数字转化为整数,和力扣12是姐妹题,我们只要明白罗马数字和整数的转换原理,就像知道十进制和二进制转换原理一样,这是一个非常下饭的一个题,可以让人非常快乐和放松,就喜欢这样的题。
让我们上快乐代码:
#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
int romanToInt(string s);
};
int Solution::romanToInt(string s) {
int ans = 0;
map<char, int>p;
p['I'] = 1;
p['V'] = 5;
p['X'] = 10;
p['L'] = 50;
p['C'] = 100;
p['D'] = 500;
p['M'] = 1000;
for (int i = 0; i < s.size()-1; i++) {
if (p[s[i]] < p[s[i + 1]]) {
ans -= p[s[i]];
}
else {
ans += p[s[i]];
}
}
ans += p[s[s.size() - 1]];
return ans;
}
int main() {
string s;
cin >> s;
Solution a;
cout << a.romanToInt(s) << endl;
return 0;
}
ヾ(◍°∇°◍)ノ゙