λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 13 - Roman to Integer (Easy)

by HandHand 2023. 4. 24.

 

πŸ’‘ 문제

LeetCode - 13번

 

🎯 풀이 κ³Όμ •

둜마 숫자λ₯Ό λ³€ν™˜ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

둜마 μˆ«μžλŠ” 감산, κ°€μ‚° 연산법을 ν•¨κ»˜ I, V, X, L, C, D, M 의 문자λ₯Ό λ‚˜μ—΄ν•˜μ—¬ ν‘œν˜„ν•©λ‹ˆλ‹€.

그렇기에 μ•ž μžλ¦¬λΆ€ν„° μˆœνšŒν•˜λ©΄μ„œ κ·Έ λ‹€μŒ μˆ«μžμ™€ 크기λ₯Ό λΉ„κ΅ν•˜μ—¬ ν•©μ‚°ν•΄μ•Όν•  크기λ₯Ό μ•Œμ•„λƒ…λ‹ˆλ‹€.

μ΄λ•Œ 반볡문 λŒ€μ‹  μž¬κ·€ ν˜ΈμΆœμ„ μ‚¬μš©ν•˜λ©΄ μ’€ 더 κ°„κ²°ν•˜κ²Œ κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

πŸ‘¨‍πŸ’» μ½”λ“œ

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    const roman = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }

    function transform(here) {
        if (here >= s.length) {
            return 0
        }

        if (here + 1 < s.length && roman[s[here]] < roman[s[here + 1]]) {
            return transform(here + 2) + roman[s[here + 1]] - roman[s[here]]
        } else {
            return transform(here + 1) + roman[s[here]]
        }
    }

    return transform(0)
};
λ°˜μ‘ν˜•

'πŸƒ algorithm > leetcode' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

LeetCode 1603 - Design Parking System (Easy)  (0) 2023.04.24
LeetCode 15 - 3Sum (Medium)  (0) 2023.04.24
LeetCode 994 - Rotting Oranges (Medium)  (0) 2023.04.24
LeetCode 24 - Swap Nodes in Pairs (Medium)  (0) 2023.02.20
LeetCode 35 - Search Insert Position (Easy)  (0) 2023.02.20

πŸ’¬ λŒ“κΈ€