Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 27, 2023 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petergi/38bd2e8205a43a1d60c30e82bcc7148e to your computer and use it in GitHub Desktop.
Save petergi/38bd2e8205a43a1d60c30e82bcc7148e to your computer and use it in GitHub Desktop.
Converts an integer to its roman numeral representation
// This updated version should be more efficient due to the constant-time lookup in the dictionary, the use of StringBuilder for efficient string concatenation, and the iteration over the lookup keys in descending order.
func toRomanNumeral(_ num: Int) -> String {
let lookup: [Int: String] = [
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"
]
var result = StringBuilder()
var remainingNum = num
for value in lookup.keys.sorted(by: >) {
while remainingNum >= value {
result.append(lookup[value]!)
remainingNum -= value
}
}
return result.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment