Roman to Int

来源:互联网 发布:linux卸载nagios 编辑:程序博客网 时间:2024/05/28 18:42

Given a roman numeral, convert it to an integer.

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

public int romanToInt(String s) {        Map roman = new HashMap();        int result = 0;        roman.put('I',1);        roman.put('V',5);        roman.put('X',10);        roman.put('L',50);        roman.put('C',100);        roman.put('D',500);        roman.put('M',1000);        for(int i=s.length()-1;i>=0;i--){            if(i==s.length()-1){                result=roman.get(s.charAt(i));                continue;            }            if(roman.get(s.charAt(i)) >= roman.get(s.charAt(i+1)))                result+=roman.get(s.charAt(i));            else                result-=roman.get(s.charAt(i));        }        return result;    }


0 0
原创粉丝点击