From 02a4031bd6fe87353cafd3cf52a146bbb43082bb Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 10 May 2020 18:41:04 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E7=BD=97=E9=A9=AC=E6=95=B0=E5=AD=97?= =?UTF-8?q?=E8=BD=AC=E6=95=B4=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 ++++++++ src/string/roman-to-integer.js | 34 ++++++++++++++++++++++++++++ test/string/roman-to-integer.test.js | 8 +++++++ 3 files changed, 52 insertions(+) create mode 100644 src/string/roman-to-integer.js create mode 100644 test/string/roman-to-integer.test.js diff --git a/README.md b/README.md index 120553f..e07f107 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,16 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/ - LintCode 422. 最后一个单词的长度 https://www.lintcode.com/problem/length-of-last-word/description +- [整数转罗马数字](src/string/integer-to-roman.js) + + - LeetCode 12. 整数转罗马数字 https://leetcode-cn.com/problems/integer-to-roman/ + - LintCode 418. 整数转罗马数字 https://www.lintcode.com/problem/integer-to-roman/description + +- [罗马数字转整数](src/string/roman-to-integer.js) + + - LeetCode 13. 罗马数字转整数 https://leetcode-cn.com/problems/roman-to-integer/ + - LintCode 419. 罗马数字转整数 https://www.lintcode.com/problem/roman-to-integer/description + ## 数组 - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js) diff --git a/src/string/roman-to-integer.js b/src/string/roman-to-integer.js new file mode 100644 index 0000000..899abe9 --- /dev/null +++ b/src/string/roman-to-integer.js @@ -0,0 +1,34 @@ +/** + * @param {string} s + * @return {number} + */ +export const romanToInt = function (s) { + const map = new Map([ + ['I', 1], + ['IV', 4], + ['V', 5], + ['IX', 9], + ['X', 10], + ['XL', 40], + ['L', 50], + ['XC', 90], + ['C', 100], + ['CD', 400], + ['D', 500], + ['CM', 900], + ['M', 1000] + ]) + + let ans = 0 + let i = 0 + while (i < s.length) { + if (i + 1 < s.length && map.has(s.substring(i, i + 2))) { + ans += map.get(s.substring(i, i + 2)) + i += 2 + } else { + ans += map.get(s.substring(i, i + 1)) + i++ + } + } + return ans +} diff --git a/test/string/roman-to-integer.test.js b/test/string/roman-to-integer.test.js new file mode 100644 index 0000000..9ecb8c5 --- /dev/null +++ b/test/string/roman-to-integer.test.js @@ -0,0 +1,8 @@ +import { romanToInt } from '../../src/string/roman-to-integer' + +test('罗马数字转整数', () => { + expect(romanToInt('III')).toBe(3) + expect(romanToInt('IV')).toBe(4) + expect(romanToInt('IX')).toBe(9) + expect(romanToInt('LVIII')).toBe(58) +})