/*
* @lc app=leetcode.cn id=13 lang=typescript
*
* [13] 罗马数字转整数
*/
// @lc code=start
function romanToInt(s: string): number {}
// @lc code=end
function romanToInt(s: string): number {
const map: { [k: string]: number } = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
let pre = s[0]
let res = map[pre]
for (let i = 1; i < s.length; i++) {
if (map[pre] >= map[s[i]]) {
res += map[s[i]]
} else {
res = res + map[s[i]] - 2 * map[pre]
}
pre = s[i]
}
return res
}
test.each([
{ input: { s: 'III' }, output: 3 },
{ input: { s: 'IV' }, output: 4 },
{ input: { s: 'IX' }, output: 9 },
{ input: { s: 'LVIII' }, output: 58 },
{ input: { s: 'MCMXCIV' }, output: 1994 },
])('input: s = $input.s', ({ input: { s }, output }) => {
expect(romanToInt(s)).toBe(output)
})