FrontEnd :-)

[LeetCode-JS] Roman to Integer 본문

JavaScript/Algorithm

[LeetCode-JS] Roman to Integer

code10 2022. 12. 8. 01:03

🙋 문제: Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

 

Constraints:

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

 

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

🅰️ 풀이:

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let result = 0;
    const strArr = s.split("");
    const hashTable = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000};
    for(let i=0; i < strArr.length; i++){
        if(hashTable[strArr[i]] < hashTable[strArr[i+1]]){
            result -= hashTable[strArr[i]];
        } else {
            result += hashTable[strArr[i]];
        }
    }
    return result;
};

>> 해쉬테이블을 공부하고 알고리즘에 처음 적용해 풀어봤다. '-')/

>> 문자열을 배열로 만들 때, split말고 스프레드 문법으로 해도 됨..  const strArr = [...s]; 

>>>> 다른 사람 풀이를 보며, 문자열만으로도 길이와 인덱스별 문자를 파악할 수 있기에.. 굳이 배열로 바꿀 필요가 없다는 걸 알았다. 확실히 빨라진다. const strArr = s.split("");

>> hashTable[strArr[i]] 이 반복되어서 변수로 저장해서 사용하면 가독성은 더 나을 것 같다.

 

다른 사람 풀이:

var romanToInt = function(s) {
    let result = 0;
    let romanHash = {
        I:1,
        V:5,
        X:10,
        L:50,
        C:100,
        D:500,
        M:1000
    }
    for(i=0; i < s.length; i++){
        if(s[i] === 'I' && s[i+1] === 'V'){
            result += 4;
            i++
        }else if(s[i] === 'I' && s[i+1] === 'X'){
            result += 9;
            i++;
        }else if(s[i] === 'X' && s[i+1] === 'L' ){
            result += 40;
            i++;
        }else if(s[i] === 'X' && s[i+1] === 'C'){
            result += 90;
            i++;
        }else if(s[i] === 'C' && s[i+1] === 'D'){
            result += 400;
            i++;
        }else if(s[i] === 'C' && s[i+1] === 'M'){
            result += 900;
            i++;
        }else{
            result += romanHash[s[i]]
        }
    }

    return result;
};

>> 로마 숫자 표기법의 특성(?)을 이해하기 쉽게 짠 코드랄까.

'JavaScript > Algorithm' 카테고리의 다른 글

[LeetCode-JS] Merge Two Sorted Lists  (0) 2022.12.15
[LeetCode-JS] Valid Parentheses  (0) 2022.12.10
[LeetCode-JS] Longest Common Prefix  (0) 2022.12.09
[LeetCode-JS] Palindrome Number  (0) 2022.12.07
[LeetCode-JS] Two Sum  (0) 2022.12.05
Comments