算法题:13. 罗马数字转整数
题
解
function romanToInt(s: string): number {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
IV: 4,
IX: 9,
XL: 40,
XC: 90,
CD: 400,
CM: 900,
};
let i = 0;
let sum = 0;
let next = '';
let v = '';
while (i < s.length) {
next = s[i + 1];
v = s[i];
if (next && map[v + next]) {
sum += map[v + next];
i += 2;
} else {
sum += map[v];
i++;
}
}
return sum;
}
评论