Last active
December 27, 2023 22:23
-
-
Save petergi/38bd2e8205a43a1d60c30e82bcc7148e to your computer and use it in GitHub Desktop.
Converts an integer to its roman numeral representation
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
// 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