首页 > 代码库 > [leetcode] Roman to Integer
[leetcode] Roman to Integer
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。