From 8967c4df196b7506b205278d5d16e1551493b4ef Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Tue, 10 Sep 2024 18:51:30 +0200 Subject: [PATCH] re-solve "13. Roman to Integer" --- .plan | 1 + src/roman_to_integer.py | 23 ++++++++++------------- tests/test_roman_to_integer.py | 1 + 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/.plan b/.plan index 69965e8..41452df 100644 --- a/.plan +++ b/.plan @@ -1,6 +1,7 @@ Sep 10, 2024 * re-solve "42. Trapping Rain Water" +* re-solve "13. Roman to Integer" Sep 9, 2024 diff --git a/src/roman_to_integer.py b/src/roman_to_integer.py index bb1faba..b0ad55d 100644 --- a/src/roman_to_integer.py +++ b/src/roman_to_integer.py @@ -1,4 +1,4 @@ -ROMAN: dict[str, int] = { +ROMAN_TO_INT = { "I": 1, "V": 5, "X": 10, @@ -10,20 +10,17 @@ class Solution: - def romanToInt(self, roman: str) -> int: - assert roman + def romanToInt(self, s: str) -> int: + n = len(s) + prev = result = ROMAN_TO_INT[s[0]] - last_int_value = ROMAN[roman[0]] - result = 0 + for i in range(1, n): + x = ROMAN_TO_INT[s[i]] - for letter in roman: - int_value = ROMAN[letter] - - if int_value > last_int_value: - result += int_value - last_int_value * 2 + if x > prev: + result += x - 2 * prev else: - result += int_value - - last_int_value = int_value + result += x + prev = x return result diff --git a/tests/test_roman_to_integer.py b/tests/test_roman_to_integer.py index 9028677..14c7ca2 100644 --- a/tests/test_roman_to_integer.py +++ b/tests/test_roman_to_integer.py @@ -10,6 +10,7 @@ ("IV", 4), ("IX", 9), ("LVIII", 58), + ("MCMXCIV", 1994), ], ) def test_solution(roman, integer):