地址:https://www.codewars.com/kata/51b66044bce5799a7f000003/train/javascript
Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Examples
RomanNumerals.toRoman(1000); // should return 'M'
RomanNumerals.fromRoman('M'); // should return 1000
例如:
describe("Tests", () => {
it("test", () => {
Test.assertEquals(RomanNumerals.toRoman(1000), 'M')
Test.assertEquals(RomanNumerals.toRoman(999), "CMXCIX")
Test.assertEquals(RomanNumerals.toRoman(4), 'IV')
Test.assertEquals(RomanNumerals.toRoman(1), 'I')
Test.assertEquals(RomanNumerals.toRoman(1991), 'MCMXCI')
Test.assertEquals(RomanNumerals.toRoman(2006), 'MMVI')
Test.assertEquals(RomanNumerals.toRoman(2020), 'MMXX')
Test.assertEquals(RomanNumerals.fromRoman('XXI'), 21)
Test.assertEquals(RomanNumerals.fromRoman('I'), 1)
Test.assertEquals(RomanNumerals.fromRoman('III'), 3)
Test.assertEquals(RomanNumerals.fromRoman('IV'), 4)
Test.assertEquals(RomanNumerals.fromRoman('MMVII'), 2007)
Test.assertEquals(RomanNumerals.fromRoman('MDCLXIX'), 1669)
});
});
自己写的方法比较简陋:
const alphaGroup = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
const toRomanMap = {
DCCCC: "CM",
CCCC: "CD",
LXXXX: "XC",
XXXX: "XL",
VIIII: "IX",
IIII: "IV",
};
const toNumberMap = {
CM: "DCCCC",
CD: "CCCC",
XC: "LXXXX",
XL: "XXXX",
IX: "VIIII",
IV: "IIII",
};
const RomanNumerals = {
toRoman: (number) => {
const res = [];
const arr = Object.keys(alphaGroup).reverse();
let i = 0;
for (i = 0; i < 7; i++) {
if (number === 0) {
break;
}
const alpha = arr[i];
let count = Math.floor(number / alphaGroup[alpha]);
number = number % alphaGroup[alpha];
while (count > 0) {
{
res.push(alpha);
count--;
}
}
}
let str = res.join("");
Object.keys(toRomanMap).forEach((label) => {
str = str.replace(label, toRomanMap[label]);
});
return str;
},
fromRoman: (str) => {
let num = 0;
Object.keys(toNumberMap).forEach((label) => {
str = str.replace(label, toNumberMap[label]);
});
str.split("").forEach((item) => {
num = alphaGroup[item] + num;
});
return num;
},
};