Problem13. Roman to Integer

来源:互联网 发布:淘宝评价怎么写好评 编辑:程序博客网 时间:2024/06/06 02:29

题目:

Given a roman numeral, convert it to an integer.

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

class Solution {    public int romanToInt(String s) {        if(s==null||s.length()==0){return 0;}        Map<Character,Integer> map=new HashMap<>();        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 len=s.length();        int result=map.get(s.charAt(len-1));        int pivort=result;        for(int i=len-2;i>=0;i--){        int curr=map.get(s.charAt(i));        if(curr>=pivort){        result+=curr;        }else{        result-=curr;        }        pivort=curr;        }        return result;    }}


原创粉丝点击