add: 罗马数字转整数

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

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
}