Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
将罗马字符转换成数字。。。。。。。。。(跟12题反着来)
解:
遍历题目给的字符串,如果前面的一个字符代表的数比后面的字符代表的数小,说明是个4这样的数(表示为IV),计算这个数应该后面减去前面。其余情况直接加上它所代表的值即可。
java代码:
public class Solution {
public int romanToInt(String s) {
if (s == null || s.length() == 0){
return -1;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
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 len = s.length();
int result = 0;
char[] cha = s.toCharArray();
for (int i = 0; i < len - 1; i++) {
if (map.get(cha[i]) < map.get(cha[i + 1])){
result -= map.get(cha[i]);
}else {
result += map.get(cha[i]);
}
}
return result + map.get(cha[len - 1]);
}
}