Roman to Integer 문제풀이 - Java 사용
로마숫자를 입력받으면 해당되는 아라비아숫자를 출력하게 하는 프로그램을 만드는 문제
필자는 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;
}
}
'LeetCode 알고리즘 문제풀이' 카테고리의 다른 글
[LeetCode-242] Valid Anagram 문제풀이 - Java 사용 (0) | 2020.09.16 |
---|---|
[LeetCode-53] Maximum Subarray 문제풀이 - Java 사용 (0) | 2020.09.15 |
[LeetCode-283] Move Zeroes 문제풀이 - Java 사용 (0) | 2020.09.13 |
[LeetCode-237] Delete Node in a Linked List 문제풀이 - Java 사용 (0) | 2020.09.12 |
[LeetCode-217] Contains Duplicate 문제풀이 - Java 사용 (0) | 2020.09.10 |