const roman ={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}varromanToInt=function(S){let ans =0for(let i =S.length-1;~i; i--){let num = roman[S.charAt(i)]if(4* num < ans) ans -= num
else ans += num
}return ans
};
Python代碼:
(跳轉(zhuǎn)至:問(wèn)題描述||解決思路)
roman ={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}classSolution:defromanToInt(self, S:str)->int:
ans =0for i inrange(len(S)-1,-1,-1):
num = roman[S[i]]if4* num < ans: ans -= num
else: ans += num
return ans
Java代碼:
(跳轉(zhuǎn)至:問(wèn)題描述||解決思路)
classSolution{publicintromanToInt(String S){int ans =0, num =0;for(int i = S.length()-1; i >=0; i--){switch(S.charAt(i)){case'I': num =1;break;case'V': num =5;break;case'X': num =10;break;case'L': num =50;break;case'C': num =100;break;case'D': num =500;break;case'M': num =1000;break;}if(4* num < ans) ans -= num;else ans += num;}return ans;}}
C++代碼:
(跳轉(zhuǎn)至:問(wèn)題描述||解決思路)
classSolution{public:intromanToInt(string S){int ans =0, num =0;for(int i = S.size()-1;~i; i--){switch(S[i]){case'I': num =1;break;case'V': num =5;break;case'X': num =10;break;case'L': num =50;break;case'C': num =100;break;case'D': num =500;break;case'M': num =1000;break;}if(4* num < ans) ans -= num;else ans += num;}return ans;}};