13. 로마 숫자를 정수로 변환 | LeetCode | Top Interview 150 | Coding Questions

발행: (2025년 12월 22일 오전 08:33 GMT+9)
1 min read
원문: Dev.to

Source: Dev.to

문제 링크

https://leetcode.com/problems/roman-to-integer/

leetcode 13

솔루션

class Solution {
    public int romanToInt(String s) {
        int n = s.length(); // length of string
        int sum = 0;
        for (int i = 0; i < n; i++) {
            char ch1 = s.charAt(i);
            if ((i + 1) < n && getVal(ch1) < getVal(s.charAt(i + 1))) {
                sum = sum - getVal(ch1);
            } else {
                sum = sum + getVal(ch1);
            }
        }
        return sum;
    }

    public int getVal(char ch) { // values of all roman numerals
        switch (ch) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
            default:
                return 0;
        }
    }
}
Back to Blog

관련 글

더 보기 »