Skip to content

Instantly share code, notes, and snippets.

@cindywu
Created January 30, 2023 23:33
Show Gist options
  • Save cindywu/cf3600df3f258ad425bb4d84bea21169 to your computer and use it in GitHub Desktop.
Save cindywu/cf3600df3f258ad425bb4d84bea21169 to your computer and use it in GitHub Desktop.
roman numeral solution
const romanNumeralKey = [
["I", 1],
["V", 5],
];
const romanNumeralLookup = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
function romanToInt(input) {
const inputAsArray = input.split("");
let total = 0;
let lastChar = "";
for (let i = 0; i < inputAsArray.length(); i++) {
let cur = inputAsArray[i];
let j = i + 1;
let next = "";
if (j < inputAsArray.length()) {
next = inputAsArray[j];
}
if (cur === "I" && (next === "X" || next === "V")) {
if (next === "X") {
total += 9;
i++;
} else {
total += 4;
i++
}
}
}
// inputAsArray.map((char) => {
// let number = romanNumeralLookup[char];
// if (lastChar === "I" && (char === "X" || char === "V")) {
// total = number - total;
// } else {
// total = total + number;
// }
// lastChar = char;
// });
return total;
}
module.exports = romanToInt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment