Skip to content

Latest commit

 

History

History
54 lines (48 loc) · 946 Bytes

13.罗马数字转整数.md

File metadata and controls

54 lines (48 loc) · 946 Bytes

13.罗马数字转整数

/*
 * @lc app=leetcode.cn id=13 lang=typescript
 *
 * [13] 罗马数字转整数
 */

// @lc code=start
function romanToInt(s: string): number {}
// @lc code=end

解法 1

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
}

Case

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)
})