Created
December 24, 2019 05:37
-
-
Save spurscho/045ea8a9a78df16ec97345c0471141ab to your computer and use it in GitHub Desktop.
13. Roman to Integer
This file contains hidden or 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
class Solution { | |
func romanToInt(_ s: String) -> Int { | |
guard s.count > 0 else { | |
return 0 | |
} | |
let arr = Array(s) | |
var resInt: Int = 0 | |
var tempVal: Character = " " | |
for i in arr { | |
switch i { | |
case "I": | |
resInt += 1 | |
break | |
case "V": | |
resInt += 5 | |
if tempVal == "I" { | |
resInt -= 2 | |
} | |
break | |
case "X": | |
resInt += 10 | |
if tempVal == "I" { | |
resInt -= 2 | |
} | |
break | |
case "L": | |
resInt += 50 | |
if tempVal == "X" { | |
resInt -= 20 | |
} | |
break | |
case "C": | |
resInt += 100 | |
if tempVal == "X" { | |
resInt -= 20 | |
} | |
break | |
case "D": | |
resInt += 500 | |
if tempVal == "C" { | |
resInt -= 200 | |
} | |
break | |
case "M": | |
resInt += 1000 | |
if tempVal == "C" { | |
resInt -= 200 | |
} | |
break | |
default : | |
break | |
} | |
tempVal = i | |
} | |
return resInt | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment