method1: 之前的太繁琐
这样写不符合程序设计,虽然可读,但不简洁。
class Solution:
def romanToInt(self, s: str) -> int:
num = 0
i = 0
while i < len(s):
if i < len(s) and s[i] == 'M':
num += 1000
i += 1
if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'M':
num += 900
i += 2
if i < len(s) and s[i] == 'D':
num += 500
i += 1
if i < len(s) - 1 and s[i] == 'C' and s[i + 1] == 'D':
num += 400
i += 2
if i < len(s) and s[i] == 'C':
num += 100
i += 1
if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'C':
num += 90
i += 2
if i < len(s) and s[i] == 'L':
num += 50
i += 1
if i < len(s) - 1 and s[i] == 'X' and s[i + 1] == 'L':
num += 40
i += 2
if i < len(s) and s[i] == 'X':
num += 10
i += 1
if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'X':
num += 9
i += 2
if i < len(s) and s[i] == 'V':
num += 5
i += 1
if i < len(s) - 1 and s[i] == 'I' and s[i + 1] == 'V':
num += 4
i += 2
if i < len(s) and s[i] == 'I':
num += 1
i += 1
return num
method 2: 2 pointers
prev指向curr的前一个数。
例一:IV:I 比 V 小, 那么执行if语句, 按正常循环,当遍历到 V时,结果为6,可见多加了一个 I,相当于 V + I = 6,
但是因为prev < curr,说明不对,需要修改错误,那么就应该是 6 - I * 2 = 4
例二:VI, 按照正常情况, 不经过if语句, 直接输出6
class Solution:
def romanToInt(self, s: str) -> int:
table = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
res = 0
prev = table['M']
for c in s:
curr = table[c]
res += curr
if prev < curr:
res -= prev * 2
prev = curr
return res
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const table = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let res = 0, prev = table['M'];
for (c of s) { // not c in s
let curr = table[c];
res += curr;
if (prev < curr) {
res -= prev * 2;
}
prev = curr
}
return res
};