package 罗马数字转整数;
import java.util.HashMap;
import java.util.Map;
public class Solution2 {
public static int romanToInt(String s) {
Map<Character, Integer> symbolValues = new HashMap<Character, Integer>(){
{
put(‘I’, 1);
put(‘V’, 5);
put(‘X’, 10);
put(‘L’, 50);
put(‘C’, 100);
put(‘D’, 500);
put(‘M’, 1000);
}
};
System.out.println(symbolValues);
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) { // s = CMXCIX
**int value = symbolValues.get(s.charAt(i));** // 因为Map的键类型为Character类型,所以此处get()里可以为char类型
if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
ans -= value; // ans = ans - value
} else {
ans += value; // ans = ans + value
}
}
return ans;
}
public static void main(String[] args) {
System.out.println(romanToInt("XLIX"));
}
}