본문 바로가기
Problem Solving/LeetCode

[LeetCode] 13. Roman to Integer - Java

by graycode 2026. 5. 10.

 문제 링크

 

Roman to Integer - LeetCode

Can you solve this real interview question? 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 tw

leetcode.com

 

 풀이 코드

public class Solution {

    public int romanToInt(String s) {
        int[] arr = {0, 0, 100, 500, 0, 0, 0, 0, 1, 0, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10};

        int sum = arr[s.charAt(s.length() - 1) - 'A'];
        for (int i = s.length() - 2; i >= 0; i--)
            sum = arr[s.charAt(i + 1) - 'A'] > arr[s.charAt(i) - 'A'] ? sum - arr[s.charAt(i) - 'A'] : sum + arr[s.charAt(i) - 'A'];

        return sum;
    }

}

댓글