代码如下:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class RomanNumber {
public static void main(String[] args) {
System.out.println("请输入一个罗马数字:");
String str = new Scanner(System.in).nextLine();
System.out.println("罗马数字转整数为:"+solution(str));
}
public static int solution(String str) {
Map<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 result = 0;
char[] arr = str.toCharArray();
if (arr.length == 1) {
return map.get(arr[0]);
} else {
for (int i = 0; i < arr.length; ) {
if (i < (arr.length-1)) {
int c1 = map.get(arr[i]);
int c2 = map.get(arr[i + 1]);
if (c1 < c2){
result += (c2 - c1);
i += 2;
}else if (c1 >= c2) {
result += c1;
i += 1;
}
}else{
result += map.get(arr[i]);
i += 1;
}
}
return result;
}
}
}