[leetcode, JS] 13. Roman to Integer

mxxn·2023년 8월 3일
0

leetcode

목록 보기
5/198

문제

문제 링크 : Roman to Integer

풀이

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let romanObj = new Map();
    romanObj.set("I", 1).set("V", 5).set("X", 10).set("L", 50).set("C", 100).set("D", 500).set("M", 1000)
    
    let sum = 0
    for(let i=0; i<s.length; i++) {
        if((s[i] === "I" && s[i+1] === "V") || (s[i] === "I" && s[i+1] === "X")) {
            sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
            i++
            continue
        }
        if((s[i] === "X" && s[i+1] === "L") || (s[i] === "X" && s[i+1] === "C")) {
            sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
            i++
            continue
        }
        if((s[i] === "C" && s[i+1] === "D") || (s[i] === "C" && s[i+1] === "M")) {
            sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
            i++
            continue
        }

        sum += romanObj.get(s[i])
    }
    
    return sum
    
};
  1. Map을 만들어 각 로마 숫자에 맞는 숫자를 set
  2. for문을 돌며 예외 사항만 체크하여 진행(4,9,40,90,400,900)
  3. sum을 return
  • Runtime 122 ms, Memory 52.1 MB

다른 풀이 1

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let map = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
    let result = 0;
    for(let i=0; i<s.length; i++) {
        let curr = map[s[i]]
        let next = map[s[i+1]]
        if(curr < next) {
            result += next-curr
            i++
        } else {
            result += curr
        }
    }
    return result
    
};
  1. 같은 방식이지만 if문을 많이 걸러냄
  2. 어차피 로마 숫자는 큰 문자부터 나오고 예외사항은 next가 curr 보다 큰 경우
  • Runtime 110 ms, Memory 47 MB

    let으로 선언한 map, curr, next를 const로 선언하면 Runtime과 Memory 효율 상승
    => Runtime 91 ms, Memory 46.9 MB

profile
내일도 글쓰기

0개의 댓글