Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
https://oj.leetcode.com/problems/roman-to-integer/思路1:从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数。
public class Solution {
public int romanToInt(String s) {
char[] symbol = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
int[] val = { 1, 5, 10, 50, 100, 500, 1000 };
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < symbol.length; i++)
map.put(symbol[i], val[i]);
int len = s.length();
int res = 0;
res += map.get(s.charAt(0));
for (int i = 1; i < len; i++) {
int cur = map.get(s.charAt(i));
int pre = map.get(s.charAt(i - 1));
if (cur <= pre) {
res += cur;
} else {
res = res + cur - 2 * pre;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(new Solution().romanToInt("MCMXC"));
}
}
参考:
http://blog.csdn.net/wzy_1988/article/details/17057929
来源:oschina
链接:https://my.oschina.net/u/1584603/blog/283587