python-algorithm

leetcode 13. Roman to Integer

무적김두칠 2023. 6. 19. 00:44

https://leetcode.com/problems/roman-to-integer/description/?envType=study-plan-v2&envId=top-interview-150 

 

Roman to Integer - LeetCode

Can you solve this real interview question? Roman to Integer - Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just tw

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def romanToInt(self, s: str-> int:
        romans_int = {'I':1,
                  'V':5,
                  'X':10,
                  'L':50,
                  'C':100,
                  'D':500,
                  'M':1000
                  }
        answer, current = 00
        for i in range(1len(s)):
            if romans_int[s[i-1]] >= romans_int[s[i]]:
                answer += romans_int[s[i-1]]
            else:
                answer -= romans_int[s[i-1]]
            current = romans_int[s[i]]
        last = romans_int[s[len(s)-1]]
        if current >= last:
            answer += last
        else:
            answer -= last
        
        if len(s) == 1:
            answer = romans_int[s[0]]
 
 
            
        return answer
cs
반응형