题目:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。
反之,减去前一个数的两倍然后加上该数。
public static int romanToInt(String s){
char[] ch={'I','V','X','L','C','D','M'};
int[] num={1,5,10,50,100,500,1000};
int cur=0,pre=0,sum=0;
HashMap<Character,Integer> map=new HashMap<Character, Integer>();
for(int i=0;i<num.length;i++)
map.put(ch[i], num[i]);
sum+=map.get(s.charAt(0));
for(int i=1;i<s.length();i++){
cur=map.get(s.charAt(i));
pre=map.get(s.charAt(i-1));
if(cur<=pre)
sum+=cur;
else
sum+=cur-2*pre;
}
return sum;
}