Created
November 28, 2019 14:41
-
-
Save soxjke/6ace830ae3881ca70b3a84ed4c34dffb to your computer and use it in GitHub Desktop.
Arabic-2-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
extension Int { | |
enum RomanDigits: 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 | |
static let max: Int = 3999 | |
static let min: Int = 1 | |
static let range = min...max | |
} | |
func romanNumber() -> String { | |
guard RomanDigits.range.contains(self) else { | |
return "OUT OF RANGE" | |
} | |
return RomanDigits | |
.allCases | |
.reversed() | |
.reduce(into: (res: "", cnt: self)) { result, digit in | |
while result.cnt >= digit.rawValue { | |
result.cnt -= digit.rawValue | |
result.res += String(describing: digit) | |
} | |
}.res | |
} | |
} | |
@discardableResult | |
func test(_ s1: String, _ s2: Int) -> Bool { | |
let condition = s1 == s2.romanNumber() | |
print("\(s1) is ROMAN \(s2) : " + (condition ? "PASS" : "FAIL")) | |
return condition | |
} | |
test("X", 10) | |
test("VII", 7) | |
test("MMMCMXCIX", 3999) | |
test("I", 1) | |
test("OUT OF RANGE", 0) | |
test("OUT OF RANGE", 4000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment