Skip to content

Commit

Permalink
re-solve "13. Roman to Integer"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 10, 2024
1 parent 607b3e7 commit 8967c4d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 13 deletions.
1 change: 1 addition & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Sep 10, 2024

* re-solve "42. Trapping Rain Water"
* re-solve "13. Roman to Integer"

Sep 9, 2024

Expand Down
23 changes: 10 additions & 13 deletions src/roman_to_integer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ROMAN: dict[str, int] = {
ROMAN_TO_INT = {
"I": 1,
"V": 5,
"X": 10,
Expand All @@ -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
1 change: 1 addition & 0 deletions tests/test_roman_to_integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
("IV", 4),
("IX", 9),
("LVIII", 58),
("MCMXCIV", 1994),
],
)
def test_solution(roman, integer):
Expand Down

0 comments on commit 8967c4d

Please sign in to comment.