Last active
August 14, 2019 06:20
-
-
Save 599316527/42d3544f34504333d1a7782d827cabc4 to your computer and use it in GitHub Desktop.
转罗马数字
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Answer to https://leetcode-cn.com/problems/integer-to-roman/ | |
function intToRoman(num) { | |
return [['X', 'V', 'I', 1], ['C', 'L', 'X', 10], ['M', 'D', 'C', 100], ['', '', 'M', 1000]] | |
.reduceRight(function (ret, item, index) { | |
let count = ~~(num / item[3]) % 10; | |
if (!count) return ret; | |
if (count % 5 == 4) return ret + item[2] + item[count > 5 ? 0 : 1]; | |
return ret + item[1].repeat(count >= 5 ? 1 : 0) + item[2].repeat(count % 5); | |
}, ''); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const charValueMapping = { | |
M: 1000, | |
D: 500, | |
C: 100, | |
L: 50, | |
X: 10, | |
V: 5, | |
I: 1 | |
}; | |
function romanToInt(s) { | |
let sum = 0; | |
let len = s.length; | |
for (let i = 0; i < len; i++) { | |
if (i + 1 < len && charValueMapping[s[i]] < charValueMapping[s[i + 1]]) { | |
sum += charValueMapping[s[i + 1]] - charValueMapping[s[i++]]; | |
} | |
else { | |
sum += charValueMapping[s[i]]; | |
} | |
} | |
return sum; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment