解題資訊
難度 : easy
程式語言 : python, javascript
解題構思
這題的解題思維有兩個部分
- 一看到有對應部分 -> hash table
羅馬字符遇到成對 “ab” 時有兩種狀況
- a >= b, 則 ans = a + b,Ex: “III” = 3、”XI” = 11
- b > a, 則 ans = a + b - 2 * a,Ex: “IX” = 1 + 10 - 2* 1 = 9
Code
Python
1 | class Solution: |
2 | def romanToInt(self, s: str) -> int: |
3 | roman_map = { |
4 | "I":1, |
5 | "V":5, |
6 | "X":10, |
7 | "L":50, |
8 | "C":100, |
9 | "D":500, |
10 | "M":1000 |
11 | } |
12 | last_num =0 |
13 | total = 0 |
14 | for roman in s: |
15 | current_num = roman_map[roman] |
16 | total+=current_num |
17 | if last_num and current_num > last_num: |
18 | total -= 2* last_num |
19 | last_num = current_num |
20 | return total |
Javascript
1 | var romanToInt = function(s) { |
2 | const roman_map = { |
3 | I: 1, |
4 | V: 5, |
5 | X: 10, |
6 | L: 50, |
7 | C: 100, |
8 | D: 500, |
9 | M: 1000 |
10 | }; |
11 | const s_len = s.length; |
12 | let last_num = 0; |
13 | let total = 0; |
14 | for (let i = 0; i < s_len; i++) { |
15 | const current_num = roman_map[s[i]]; |
16 | total += current_num; |
17 | if (last_num && current_num > last_num) { |
18 | total -= 2 * last_num; |
19 | } |
20 | last_num = current_num; |
21 | } |
22 | return total; |
23 | }; |