Skip to content

Instantly share code, notes, and snippets.

@geor-kasapidi
Created February 1, 2020 13:00
Show Gist options
  • Save geor-kasapidi/23b0e1ee79892ebfea970723fbcc9482 to your computer and use it in GitHub Desktop.
Save geor-kasapidi/23b0e1ee79892ebfea970723fbcc9482 to your computer and use it in GitHub Desktop.
class Solution {
func myAtoi(_ str: String) -> Int {
var value = 0
var hasValue = false
var isNegative = false
let max = (1 << 31) - 1
let min = -(1 << 31)
LOOP: for c in str {
if let digit = c.wholeNumberValue {
hasValue = true
if isNegative {
if min + digit > -value * 10 {
return min
}
} else {
if max - digit < value * 10 {
return max
}
}
value = value * 10 + digit
continue
}
if hasValue {
break
}
switch c {
case "+":
hasValue = true
case "-":
hasValue = true
isNegative = true
case " ":
continue
default:
break LOOP
}
}
return isNegative ? -value : value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment