-
Notifications
You must be signed in to change notification settings - Fork 41
/
13.swift
64 lines (52 loc) · 1.31 KB
/
13.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// RomanToInteger.swift
// RomanToInteger
//
// Created by Lex on 4/25/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*/
import Foundation
import XCTest
extension String {
func romanToInteger() -> Int {
var result = 0
for c in Array(self.reversed()) {
switch c {
case "I":
result += result >= 5 ? -1 : 1
break
case "V":
result += 5
break
case "X":
result += 10 * (result >= 50 ? -1 : 1)
break
case "L":
result += 50
break
case "C":
result += 100 * (result >= 500 ? -1 : 1)
break
case "D":
result += 500
break
case "M":
result += 1000
break
default: ()
}
}
return result
}
}
class RomanToIntegerTest: XCTestCase {
func testRomanToInteger() {
XCTAssertEqual("X".romanToInteger(), 10, "")
XCTAssertEqual("XII".romanToInteger(), 12, "")
XCTAssertEqual("XV".romanToInteger(), 15, "")
}
}