Created
April 26, 2021 02:28
-
-
Save zohaib304/4c94405e6009c3e290a36c234148e7ba to your computer and use it in GitHub Desktop.
13 - Roman to Integer - LeetCode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def romanToInt(self, s: str) -> int: | |
def value(r): | |
if (r == 'I'): | |
return 1 | |
if (r == 'V'): | |
return 5 | |
if (r == 'X'): | |
return 10 | |
if (r == 'L'): | |
return 50 | |
if (r == 'C'): | |
return 100 | |
if (r == 'D'): | |
return 500 | |
if (r == 'M'): | |
return 1000 | |
return -1 | |
res = 0 | |
i = 0 | |
while(i < len(s)): | |
s1 = value(s[i]) | |
if(i + 1 < len(s)): | |
s2 = value(s[i+1]) | |
if(s1 >= s2): | |
res = res + s1 | |
i = i + 1 | |
else: | |
res = res + s2 - s1 | |
i = i + 2 | |
else: | |
res = res + s1 | |
i = i + 1 | |
return res | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment