罗马数字转整数(简单)
思路:
-
HashMap
建立罗马字符到数值的映射表。 -
遍历罗马字符串,比较当前字符和下一位字符的值:
-
如果当前字符的值 ≥ 下一位的值,则直接累加当前值。
-
如果当前字符的值 < 下一位的值,则减去当前值(如
IV
是5-1=4
)。
-
-
最后一位字符 直接累加其值。
代码:
class Solution {public int romanToInt(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 res=0;for(int i=0;i<s.length();i++){int current=map.get(s.charAt(i));if(i<s.length()-1&¤t<map.get(s.charAt(i+1))){res-=current;}else{res+=current;}}return res;}
}