Skip to content

Instantly share code, notes, and snippets.

@perjerz
Created June 17, 2022 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perjerz/f4b0c802d0f47ef3c904ba46bc752669 to your computer and use it in GitHub Desktop.
Save perjerz/f4b0c802d0f47ef3c904ba46bc752669 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/roman-to-integer/submissions/
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const map = new Map();
map.set('I', 1);
map.set('V', 5);
map.set('X', 10);
map.set('L', 50);
map.set('C', 100);
map.set('D', 500);
map.set('M', 1000);
let sum = map.get(s[s.length - 1]);
for (let i = s.length - 1; i >= 1; i--) {
const last1 = map.get(s[i]);
const last2 = map.get(s[i-1]);
if (last2 < last1) {
sum -= last2;
} else {
sum += last2;
}
}
return sum;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment