LeetCode 13 Roman to Integer

来源:互联网 发布:大学生就业压力知乎 编辑:程序博客网 时间:2024/06/06 19:38

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

小数字在大数字前面表示的数是用大数字减去小数字,如 IV=4;
小数字在大数字后面表示的数是用大数字加上小数字,如VII=7;

public int romanToInt(String s) {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 value = map.get(s.charAt(0));for (int i = 1; i < s.length(); i++) {if (map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {value = value + map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1));} else {value = value + map.get(s.charAt(i));}}return value;}





0 0
原创粉丝点击