Skip to content

Latest commit

 

History

History
58 lines (51 loc) · 1012 Bytes

13.-roman-to-integer.md

File metadata and controls

58 lines (51 loc) · 1012 Bytes

13. Roman to Integer

{% tabs %} {% tab title="Go" %}

func romanToInt(s string) int {
    d := map[byte]int{
		'I': 1,
		'V': 5,
		'X': 10,
		'L': 50,
		'C': 100,
		'D': 500,
		'M': 1000,
	}
    var ans int
    var prev int
    if len(s) == 0 {
        return ans
    }
    for i:=len(s)-1; i>= 0 ; i-- {
        if d[s[i]] < prev{
            ans -= d[s[i]]
        } else {
            ans += d[s[i]]
            prev = d[s[i]]
        }
        
    }
    return ans
}   

{% endtab %}

{% tab title="Python" %}

class Solution:
    def romanToInt(self, s: str) -> int:
        d = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
        ans = 0
        if not s:
            return ans
        prev = 0
        ### 反向遍历
        for i in range(len(s)-1,-1,-1):
            if d[s[i]] < prev:
                ans -= d[s[i]]
            else:
                ans += d[s[i]]
                prev = d[s[i]]
            
        return ans 

{% endtab %} {% endtabs %}