Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 27, 2023 22:19
Show Gist options
  • Select an option

  • Save petergi/b08641a24532691554e03a39464b7a05 to your computer and use it in GitHub Desktop.

Select an option

Save petergi/b08641a24532691554e03a39464b7a05 to your computer and use it in GitHub Desktop.
Converts an integer to its roman numeral representation
/**
* Converts a given number to a Roman numeral representation.
*
* @param {number} num - The number to be converted.
* @return {string} The Roman numeral representation of the given number.
*/
function toRomanNumeral(num) {
const lookup = new Map([
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"],
])
let result = ""
for (const [value, symbol] of lookup) {
while (num >= value) {
result += symbol
num -= value
}
}
return result
}
toRomanNumeral(3) //= 'III'
toRomanNumeral(11) //= 'XI'
toRomanNumeral(1998) //= 'MCMXCVIII'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment