LeetCode OJ --问题与解答 Roman to Integer

来源:互联网 发布:酷狗音乐 mac 编辑:程序博客网 时间:2024/06/10 14:49
题目


Given a roman numeral, convert it to an integer.

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

把罗马数字(String表示)变成整数


思路


1 先查谷歌了解罗马数字的表示为何

2 确定后,马上想到HashMap可以用数字对应字符,然后一个个加起来。

3 难点是4和9 的部分,怎么处理。

4 可以看到只要字符代表的数 后面的比前面小,那么就要用后面的减去前面的。可是之前,我们每次都是做加法,所以这里就减两次前面的就可以了。


代码


public class Solution {    public int romanToInt(String s) {        if(s.length()==0){            return 0;        }        HashMap<Character,Integer> record = new HashMap<Character,Integer>();        record.put('I',1);        record.put('V',5);        record.put('X',10);        record.put('L',50);        record.put('C',100);        record.put('D',500);        record.put('M',1000);                char[] c = s.toCharArray();        int pre = record.get(c[0]);        int ans = record.get(c[0]);        for(int i= 1;i<c.length;i++){            int cur = record.get(c[i]);            if(cur<=pre){                ans+=cur;                            }            else{                ans=ans+cur-2*pre;            }            pre=cur;        }        return ans;            }}



0 0