add: 罗马数字转整数

This commit is contained in:
yi-ge 2020-05-10 18:41:04 +08:00
parent 1cacc57721
commit 02a4031bd6
3 changed files with 52 additions and 0 deletions

View File

@ -76,6 +76,16 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/ - LeetCode 58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/
- LintCode 422. 最后一个单词的长度 https://www.lintcode.com/problem/length-of-last-word/description - 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) - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)

View File

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

View File

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