문제에 대한 자세한 정보는 LeetCode | 13. Roman to Integer에서 확인할 수 있다.
처음에는 문제를 엉뚱하게 해석해서 복잡하게 풀다가 다시 읽어보고 푼 문제다.
로마 숫자는 보통 왼쪽에서 오른쪽으로 가장 큰 숫자부터 쓰는데 이 경우에는 symbol에 따른 value를 각각 더해주면 된다.
하지만 4는 IIII가 아닌 I(1)V(5)이다. V는 5이고 1인 I를 빼서 IV(4)가 되는 것이다. 왼쪽에서 가장 큰 숫자부터 쓴 경우가 아니다. symbol에 따른 value를 더해주는 것이 아닌 빼줘야 한다.
class Solution {
public int romanToInt(String s) {
int output = 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);
output = map.get(s.charAt(s.length() - 1));
for(int i = s.length() - 2; i >= 0; i--) {
if(map.get(s.charAt(i)) >= map.get(s.charAt(i + 1)))
output += map.get(s.charAt(i));
else
output -= map.get(s.charAt(i));
}
return output;
}
}
Memory Usage : 39.5 MB, less than 57.51% of Java online submissions for Roman to Integer.
Runtime : 5 ms, faster than 69.39% of Java online submissions for Roman to Integer.
백준과는 달리 문제가 전부 영어로 되어있기 때문에 문제 읽는 시간이 조금 더 걸린다. 난이도는 Easy라고 되어있는데 나한테 Easy하지 않은 문제도 있다... 문제를 풀고 Discuss에서 다른 사람의 풀이를 보거나 여러 의견을 읽는 것도 중요한 것 같다.