此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 13. Roman to Integer

解題思路

暴力破解法呵呵
不過在了解題目為羅馬數字後有了不同的想法~
(一開始我以為輸入是亂數嗚嗚 下次會好好看題目的!)

我滴程式碼

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution:
def romanToInt(self, s: str) -> int:
i = 0
sum = 0
while(i < len(s)):
if(s[i] == "I"):
if(i + 1 < len(s)):
if(s[i+1] == "V"):
sum = sum + 4
i = i + 2
elif(s[i+1] == "X"):
sum = sum + 9
i = i + 2
else:
sum = sum + 1
i = i + 1
else:
sum = sum + 1
i = i + 1
elif(s[i] == "X"):
if(i + 1 < len(s)):
if(s[i+1] == "L"):
sum = sum + 40
i = i + 2
elif(s[i+1] == "C"):
sum = sum + 90
i = i + 2
else:
sum = sum + 10
i = i + 1
else:
sum = sum + 10
i = i + 1
elif(s[i] == "C"):
if(i + 1 < len(s)):
if(s[i+1] == "D"):
sum = sum + 400
i = i + 2
elif(s[i+1] == "M"):
sum = sum + 900
i = i + 2
else:
sum = sum + 100
i = i + 1
else:
sum = sum + 100
i = i + 1
elif(s[i] == "V"):
sum = sum + 5
i = i + 1
elif(s[i] == "L"):
sum = sum + 50
i = i + 1
elif(s[i] == "D"):
sum = sum + 500
i = i + 1
elif(s[i] == "M"):
sum = sum + 1000
i = i + 1
return sum