package Java_18_2.src;
import java.util.HashMap;
public class Practice1 {
public static void solution(String s) {
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);
int sum = 0;
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length - 1; i++) {
if (map.get(arr[i]) < map.get(arr[i + 1])) {
sum -= map.get(arr[i]);
} else {
sum += map.get(arr[i]);
}
}
// 마지막 값은 for문 연산에 포함이 안되므로 따로 작성
sum += map.get(arr[arr.length - 1]);
System.out.println(sum);
}
public static void main(String[] args) {
// Test code
solution("III");
solution("IV");
solution("VI");
solution("XIII");
solution("XXVI");
solution("MCMXCIV");
}
}
package Java_18_2.src;
public class Practice2 {
public static String solution(int num){
String result = "";
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
int i = 0;
while (num > 0) {
while (num >= values[i]) {
num -= values[i];
result += roman[i];
}
i++;
}
return result;
}
public static void main(String[] args) {
// Test code
System.out.println(solution(3));
System.out.println(solution(4));
System.out.println(solution(6));
System.out.println(solution(13));
System.out.println(solution(26));
System.out.println(solution(1994));
}
}
'개발 공부 > 문제와 풀이' 카테고리의 다른 글
Java) 연습문제 3-1 (0) | 2024.08.10 |
---|---|
Java) 연습문제 2-2 (0) | 2024.08.10 |
Java) 물을 가장 많이 담을 수 있는 면적 구하기 (0) | 2024.08.09 |
Java) replace 구현 문제 (0) | 2024.08.09 |
객체 지향 프로그래밍 문제와 풀이 (0) | 2024.03.23 |