Skip to content

Instantly share code, notes, and snippets.

@soxjke soxjke/main.swift
Created Nov 28, 2019

Embed
What would you like to do?
Arabic-2-Roman
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
You can’t perform that action at this time.