문제설명
로마 숫자를 정수로 변환하라
로만 숫자는 다음 7가지 심볼로 표현된다.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
문제풀이
enum Roman: Int{
case I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
static func parse(_ char: Character) -> Int {
switch char {
case "I" :
return I.rawValue
case "V" :
return V.rawValue
case "X" :
return X.rawValue
case "L" :
return L.rawValue
case "C" :
return C.rawValue
case "D" :
return D.rawValue
case "M" :
return M.rawValue
default : return 0
}
}
}
func romanToInt(_ s: String) -> Int {
var total = 0
let arr = Array(s)
var i = 0
while i < arr.count {
if i+1 < arr.count && Roman.parse(arr[i]) < Roman.parse(arr[i+1]) {
total += Roman.parse(arr[i+1]) - Roman.parse(arr[i])
i = i+2
} else {
total += Roman.parse(arr[i])
i = i+1
}
}
return total
}
print(romanToInt("I")) //1
print(romanToInt("V")) //5
print(romanToInt("VI")) //6
print(romanToInt("IV")) //4
print(romanToInt("CMXCIV")) //994
'알고리즘풀이' 카테고리의 다른 글
LeetCode: Hamming Distance, 해밍 거리 (0) | 2021.03.21 |
---|---|
LeetCode: Number of 1 Bits (0) | 2021.03.20 |
LeetCode: Is Power Of Three (0) | 2021.03.16 |
LeetCode: Best Time to Buy and Sell Stock (0) | 2021.03.01 |
LeetCode: Climbing Stairs (0) | 2021.02.26 |