Created
February 20, 2024 08:49
-
-
Save chiliec/b0d52748735468b072eb28d6cb925bae to your computer and use it in GitHub Desktop.
12. 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
/** | |
* Question Link: https://leetcode.com/problems/integer-to-roman/ | |
*/ | |
class Solution { | |
enum Roman: Int, CaseIterable { | |
case I = 1 | |
case IV = 4 | |
case V = 5 | |
case IX = 9 | |
case X = 10 | |
case XL = 40 | |
case L = 50 | |
case XC = 90 | |
case C = 100 | |
case CD = 400 | |
case D = 500 | |
case CM = 900 | |
case M = 1000 | |
} | |
func intToRoman(_ num: Int) -> String { | |
var num = num | |
var result = "" | |
var allCases = Roman.allCases | |
let allCasesReversed = allCases.reversed() | |
for r in allCasesReversed { | |
while num % r.rawValue != num && num > 0 { | |
result += "\(r)" | |
num -= r.rawValue | |
} | |
} | |
return result | |
} | |
} | |
Solution().intToRoman(3) == "III" | |
Solution().intToRoman(58) == "LVIII" | |
Solution().intToRoman(1994) == "MCMXCIV" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment