LeetCode 알고리즘 문제풀이

[LeetCode-13] Roman to Integer 문제풀이 - Java 사용

줄라이퍼스트 2020. 9. 14. 18:11

 Roman to Integer 문제풀이 - Java 사용

input값을 넣으면 해당되는 output값으로 나와야 한다.

 

구글번역기를 이용하여 번역

로마숫자를 입력받으면 해당되는 아라비아숫자를 출력하게 하는 프로그램을 만드는 문제

필자는 map인터페이스  hashmap을이용하여 key와 value값을 저장하여 get메소드를 이용하여 문제를 풀었다

 

package leetcode13;

import java.util.HashMap;

public class Solution {

	public static void main(String[] args) {
		String s = "IX";
		romanToInt(s);
	}
	// ex) IX(9)로 받았을 때 기준
	public Static int romanToInt(String s) {
			
            System.out.println(s.length());
			int res = 0;
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            map.put('I', 1);
            map.put('V', 5);
            map.put('X', 10);
            map.put('L', 50);
            map.put('C', 100);
            map.put('D', 500);
            map.put('M', 1000);

            // 주어진 키가 있는 값을 리턴
            res += map.get(s.charAt(0));
            for (int i = 1; i < s.length(); i++) {
                int cur = map.get(s.charAt(i)); // charAt(1)는 10 cur 값 ->10
                int pre = map.get(s.charAt(i - 1));//charAt(0)는 10 pre 이전 값 ->1
                // res = res - pre * 2
                // 1 = 1 - 1 * 2 = -1
                // res = 10 - 1 
                if (pre < cur)// 1<10 조건에 해당
                    res -= pre * 2; // res = 1-1*2
                res += cur; // res = res + cur -> 9
            }
        return res;
    }
}