Skip to content

Instantly share code, notes, and snippets.

@caglarorhan
Created July 28, 2022 02:03
Show Gist options
  • Save caglarorhan/b4b8ff501ce21f707c769bd690d994e7 to your computer and use it in GitHub Desktop.
Save caglarorhan/b4b8ff501ce21f707c769bd690d994e7 to your computer and use it in GitHub Desktop.
convert Roman numbers to integer
var romanToInt = function(s) {
let num=0;
let romans ={
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
// "MCMXCIV"
let prev=null;
for(let i=0; i<s.length; i++){
if(prev!==null && romans[prev]<romans[s[i]]){
num=num - 2*parseInt(romans[prev]) + parseInt(romans[s[i]]);
}else{
num=num+parseInt(romans[s[i]])
}
prev=s[i];
}
return num;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment