아주 단순하게 switch문으로 하나하나...^^ 해봄
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const target = s;
const length = target.length;
let answer = 0;
for(let i=0;i<length;i++) {
switch(target[i]) {
case "I":
if(target[i+1] === "V" || target[i+1] === "X") {
break;
}
answer+=1;
break;
case "V":
if(target[i-1] === "I") {
answer+=4;
break;
}
answer+=5;
break;
case "X":
if(target[i+1] === "L" || target[i+1] === "C") {
break;
}
if(target[i-1] === "I") {
answer+=9;
break;
}
answer+=10;
break;
case "L":
if(target[i-1] === "X") {
answer+=40;
break;
}
answer+=50;
break;
case "C":
if(target[i+1] === "D" || target[i+1] === "M") {
break;
}
if(target[i-1] === "X") {
answer+=90;
break;
}
answer+=100;
break;
case "D":
if(target[i-1] === "C") {
answer+=400;
break;
}
answer+=500;
break;
case "M":
if(target[i-1] === "C") {
answer+=900;
break;
}
answer+=1000;
break;
}
}
return answer;
};
Runtime: 197 ms
Memory Usage: 47.3 MB
문제를 잘 읽어보면 Roman numerals are usually written largest to smallest from left to right.
라고 써있다. 그럼 작은 수가 먼저 오는 경우를 찾아주면 되겠구나.. 이래서 문제를 잘 읽으라는 거구나...
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const length = s.length;
let answer = 0;
const roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
for(let i=0;i<length;i++) {
const prev = roman[s[i-1]];
const curr = roman[s[i]];
answer += (prev && prev<curr) ? curr-2*prev : curr;
}
return answer;
};
Runtime: 174 ms
Memory Usage: 47 MB