import java.util.HashMap;
import java.util.Map;
public class Solution {
public int romanToInt(String s) {
Map<Character, Integer> romanMap = new HashMap<>();
romanMap.put('I', 1);
romanMap.put('V', 5);
romanMap.put('X', 10);
romanMap.put('L', 50);
romanMap.put('C', 100);
romanMap.put('D', 500);
romanMap.put('M', 1000);
int preValue = Integer.MAX_VALUE;
int temp = 0;
int sum = 0;
for(int i = 0; i < s.length(); i++){
int currValue = romanMap.get(s.charAt(i));
if(currValue < preValue){
sum += temp;
temp = currValue;
}else if(currValue == preValue){
temp += currValue;
}else {
temp = currValue - temp;
}
preValue = currValue;
}
return sum + temp;
}
public static void main(String[] args){
System.out.println(new Solution().romanToInt("XIX"));
}
}
罗马数字转换
最新推荐文章于 2022-10-28 19:40:37 发布