13. Roman to Integer

import java.util.HashMap;
import java.util.Map;

public class RomanToInt13 {
    public static  int romanToInt(String s) {
        int sum=0;
        int i=0;
        Map<Character,Integer> ret=new HashMap();
        ret.put('I',1) ;
        ret.put('V',5) ;
        ret.put('X',10) ;
        ret.put('L',50) ;
        ret.put('C',100) ;
        ret.put('D',500) ;
        ret.put('M',1000) ;
        while(i<s.length()){
            if(i+1<s.length()&&(ret.get(s.charAt(i))<ret.get(s.charAt(i+1)))){
                sum-=ret.get(s.charAt(i));
            }else{
                sum+=ret.get(s.charAt(i));
            }
            i++;
        }

        return sum;
    }

    public static void main(String[] args) {

        System.out.println(romanToInt("MCMXCIV"));

    }


}

  

posted @ 2020-06-07 15:13  lalalalatxx  阅读(90)  评论(0编辑  收藏  举报