The Roman to Integer solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Roman to Integer
C++, Python and TypeScript solutions for Roman to Integer.
Solution files
Python•roman-to-integer/synced-solution.py
class Solution:
def romanToInt(self, s: str) -> int:
vals = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
res = 0
for i in range(len(s)):
if i+1 < len(s) and vals[s[i]] < vals[s[i+1]]:
res -= vals[s[i]]
else:
res += vals[s[i]]
return res
C++•roman-to-integer/synced-solution.cpp
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int> vals={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int res = 0;
for (int i = 0; i < s.size(); i++) {
if (i+1 < s.size() && vals[s[i]] < vals[s[i+1]]) res -= vals[s[i]];
else res += vals[s[i]];
}
return res;
}
};
TypeScript•roman-to-integer/synced-solution.ts
function romanToInt(s: string): number {
const vals: {[k:string]:number} = {I:1,V:5,X:10,L:50,C:100,D:500,M:1000};
let res = 0;
for (let i = 0; i < s.length; i++) {
if (i+1 < s.length && vals[s[i]] < vals[s[i+1]]) res -= vals[s[i]];
else res += vals[s[i]];
}
return res;
}