Roman to Integer: Position Logic

Jay·2022년 6월 1일
0

Grind 120

목록 보기
27/38



First Thoughts: symbol and value should be connected, meaning we should construct a map of character and integer? It's important to construct the logic of calculating these roman numerals (keyword "after" and "before"). Same character symbol can result in subtraction and addition -> need some logic to differentiate between the two.

My Solution:

public int romanToInt(String s) {
	int ret = 0;
    HashMap<Character, Integer> map = new HashMap<>();
    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);
    for (int i=0; i<s.length()-1; i++) {
    	if (map.get(s.charAt(i))<map.get(s.charAt(i+1)) {
        	ret -= map.get(s.charAt(i));
        }
        else ret += map.get(s.charAt(i));
    }
    ret += map.get(s.charAt(s.length()-1));
    return ret;
}

Catch Point

  1. Fully understanding and "codifying" the logic behind the calculation (perhaps trace your thoughts, how you yourself ended up in that answer) is the main key to constructing the solution.

  2. In this case, the crucial point was to differentiate whether the same character meant subtraction or addition -> based on its position (whether the value of the character after is greater / smaller than itself).

  3. Characters themselves don't hold values -> construction of map

  4. Last character always adds to the calculation in roman numerals.

0개의 댓글