string-to-integer-atoi

This commit is contained in:
Gleb Koval 2021-11-09 11:42:53 +00:00
parent b2cb398c71
commit 6b0e32d66a
No known key found for this signature in database
GPG Key ID: 7C89CDC822F8392B
1 changed files with 29 additions and 0 deletions

View File

@ -0,0 +1,29 @@
package main
var MIN, MAX = -(1 << 31), (1 << 31) - 1
func myAtoi(s string) int {
m, n, c := 1, true, 0
for _, char := range s {
if n && char == ' ' {
continue
} else if n && char == '-' {
m = -1
} else if !(n && char == '+') {
char_n := int(char - '0')
if char_n < 0 || char_n > 9 {
break
}
c *= 10
c += char_n
if c < 0 || c > MAX {
if m == 1 {
return MAX
}
return MIN
}
}
n = false
}
return c * m
}