Given a roman numeral, convert it to an integer. java
Input is guaranteed to be within the range from 1 to 3999. .net
https://oj.leetcode.com/problems/roman-to-integer/思路1:從前向後遍歷羅馬數字,若是某個數比前一個數小,則加上該數。反之,減去前一個數的兩倍而後加上該數。 code
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")); } }
參考: blog
http://blog.csdn.net/wzy_1988/article/details/17057929 leetcode