Created
June 17, 2022 19:16
-
-
Save perjerz/f4b0c802d0f47ef3c904ba46bc752669 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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