标签:class blog code java http tar
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
[leetcode] Roman to Integer,布布扣,bubuko.com
标签:class blog code java http tar
原文地址:http://www.cnblogs.com/jdflyfly/p/3810686.html