Created
December 24, 2019 04:21
-
-
Save spurscho/fdc80d638ca2fc52de66c9fdf3bbb4a7 to your computer and use it in GitHub Desktop.
8. String to Integer (atoi)
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 myAtoi(_ str: String) -> Int { | |
guard str.count > 0 else { | |
return 0 | |
} | |
var trimmedStr = str.trimmingCharacters(in: .whitespaces) | |
guard trimmedStr.count > 0 else { | |
return 0 | |
} | |
var resStr: String = "" | |
var isMinus = false | |
if trimmedStr.first! == "-" { | |
isMinus = true | |
trimmedStr.removeFirst() | |
} else if trimmedStr.first! == "+" { | |
trimmedStr.removeFirst() | |
} | |
var arr = Array(trimmedStr) | |
for i in 0 ..< arr.count { | |
if arr[i].isNumber == false { | |
break | |
} | |
resStr += "\(arr[i])" | |
} | |
if isMinus == true { | |
resStr = "-\(resStr)" | |
} | |
guard let resDouble = Double(resStr) else { | |
return 0 | |
} | |
if resDouble > Double(Int32.max) { | |
return Int(Int32.max) | |
} | |
if resDouble < Double(Int32.min) { | |
return Int(Int32.min) | |
} | |
let resInt = Int(resDouble) | |
return resInt | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment