DEV Community

Discussion on: Solution: Roman to Integer

Collapse
 
gaweki profile image
Andrel Karunia S

hello there

i have not checked yet the speed, but this accepted

Javascript solution:

var romanToInt = function(s) {
const roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
let ans = 0
for(let i = 0; i < s.length; i++){
if(roman[s[i]] < roman[s[i+1]]){
ans -= roman[s[i]]
} else {
ans += (roman[s[i]] || 0) // still accepted using zero or not
}
}
return ans
};

Idea:

  • number reduced if the next number bigger than current number
  • number added if next number is smaller than or equal the current number