13. Roman to Integer

来源:互联网 发布:linux下的echo命令 编辑:程序博客网 时间:2024/05/16 10:05

Given a roman numeral, convert it to an integer.

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

public class Solution {    public int romanToInt(String s) {        Map<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 result = 0;        for (int i = 0; i < s.length(); i++) {            char ch = s.charAt(i);            if (i == 0) {                result += map.get(ch);            } else {                char prev = s.charAt(i - 1);                if (map.get(ch) > map.get(prev)) {                    result += map.get(ch);                    result -= map.get(prev) * 2;                } else {                    result += map.get(ch);                }            }        }        return result;    }}
0 0
原创粉丝点击