题目描述:
Given a roman numeral, convert it to aninteger.
Input is guaranteed to be within the rangefrom 1 to 3999.
题目理解:
给定一个罗马数字(字符串的形式),将其转换成一个整数,范围是1到3999
分析:
1. 罗马数字1到10为:I,II,III,IV,V,VI,VII,VIII,IX,X
2. I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
3. 观察“左减右加”的规律,左边的字符代表l的数子比紧挨的右边r小,则该l代表-l;繁殖如果l>=r,代表+l
4. 从字符串的末尾开始到启始位置遍历字符串,如果当前的字符代表的数字比上一个小,则result -= 当前字符代表的数字;如果当前字符代表的数字>=上一个,则result += 当前字符代表的数字
解答:
public int romanToInt(String s) {
Map<Character, Integer> charToInt = new HashMap<Character,Integer>();
charToInt.put('I',1);
charToInt.put('V',5);
charToInt.put('X',10);
charToInt.put('L',50);
charToInt.put('C',100);
charToInt.put('D',500);
charToInt.put('M',1000);
int result = 0;
int pre = 0;
int cur = 0;
char[] nums = s.toCharArray();
for(int i = s.length() - 1; i >= 0; i--){
cur = charToInt.get(nums[i]);
if(cur >= pre) result += cur;
else result -= cur;
pre = cur;
}
return result;
}