Skip to content

Instantly share code, notes, and snippets.

@599316527
Last active August 14, 2019 06:20
Show Gist options
  • Save 599316527/42d3544f34504333d1a7782d827cabc4 to your computer and use it in GitHub Desktop.
Save 599316527/42d3544f34504333d1a7782d827cabc4 to your computer and use it in GitHub Desktop.
转罗马数字
// 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);
}, '');
};
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