Leetcode 13. Roman to Integer
https://leetcode.com/problems/roman-to-integer/
#include<map>
using namespace std;
class Solution {
public:
map<char,int> AA={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int romanToInt(string s) {
int ans=0;
for(int i=0;i<s.size()-1;++i){
if(AA[s[i+1]]>AA[s[i]]) ans-=AA[s[i]];
else ans+=AA[s[i]];
}
return ans+AA[s.back()];
}
};
python版本
class Solution:
def romanToInt(self, s: str) -> int:
dic={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
ans=0
for i in range(len(s)):
if i==len(s)-1:
ans+=dic[s[i]]
else:
if dic[s[i]]>=dic[s[i+1]]:
ans+=dic[s[i]]
else:
ans-=dic[s[i]]
return ans