Last active
February 26, 2021 11:00
-
-
Save sashagra/ed147fd787237be8660e1757e8f58deb to your computer and use it in GitHub Desktop.
javascripr implementation of convert integer to roman
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 convertToRoman = num => { | |
const numbers = { | |
"1X": "I", | |
"1V": "V", | |
"2X": "X", | |
"2V": "L", | |
"3X": "C", | |
"3V": "D", | |
"4X": "M" | |
} | |
const numString = num.toString() | |
const digitsRom = [] | |
for (let i = 0; i < numString.length; i++) { | |
const digit = numString.length - i | |
const symbols = { | |
1: numbers[digit + "X"], | |
5: numbers[digit + "V"], | |
10: numbers[digit + 1 + "X"] | |
} | |
const digitInt = +numString[i] | |
if (digitInt <= 0) { | |
digitsRom.push("") | |
} else if (digitInt < 4) { | |
let n = "" | |
for (let i = 0; i < digitInt; i++) { | |
n += symbols[1] | |
} | |
digitsRom.push(n) | |
} else if (digitInt === 4) { | |
digitsRom.push(symbols[1] + symbols[5]) | |
} else if (digitInt === 5) { | |
digitsRom.push(symbols[5]) | |
} else if (digitInt < 9) { | |
let n = symbols[5] | |
for (let i = 5; i < digitInt; i++) { | |
n += symbols[1] | |
} | |
digitsRom.push(n) | |
} else { | |
digitsRom.push(symbols[1] + symbols[10]) | |
} | |
} | |
return digitsRom.join("") | |
} | |
console.log(convertToRoman(905)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment