卖萌的弱渣

I am stupid, I am hungry.

Roman to Integer

Given a roman numeral, convert it to an integer.

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

Solution

  • Java: s[i] <s[i+1]
(Roman-to-Integer.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int romanToInt(String s) {
        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        hm.put('M',1000);
        hm.put('D',500);
        hm.put('C',100);
        hm.put('L',50);
        hm.put('X',10);
        hm.put('V',5);
        hm.put('I',1);
        int ret = 0;
        for(int i=0;i<s.length()-1;i++){
            if(hm.get(s.charAt(i))<hm.get(s.charAt(i+1)))
                ret -= hm.get(s.charAt(i));
            else
                ret += hm.get(s.charAt(i));
        }
        return ret+hm.get(s.charAt(s.length()-1));
    }
}
  • Python: 要区分几个特殊情况,CM, IV, IX
(Roman-to-Integer.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        R2Imap = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
        ret = 0
        if s == "":
            return ret

        index = len(s)-2
        while index >=0:
            # CM, IV, IX 
            if R2Imap[s[index]] < R2Imap[s[index+1]]:
                ret -= R2Imap[s[index]]
            else:
            # M,D,C,L,X,V,I
                ret += R2Imap[s[index]]
            index -= 1
        # s[len(s)-1]
        ret += R2Imap[s[-1]]
        return ret