You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
827 B

package atoi
import (
"math"
"regexp"
"strings"
)
var pattern, _ = regexp.Compile(`^\s*([-+]?)(\d+)`)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func bound(num, low, hi int) int {
return min(max(low, num), hi)
}
func myAtoi(s string) int {
groups := pattern.FindStringSubmatch(s)
if groups == nil {
return 0
}
sign := 1
if groups[1] == "-" {
sign = -1
}
digits := strings.TrimLeft(groups[2], "0")
size := len(digits)
if size > 10 {
return bound(math.MaxInt64*sign, math.MinInt32, math.MaxInt32)
}
result := 0
for i, d := range digits {
val := int(d) - 48
result += int(math.Pow10(size-i-1)) * val
}
return bound(result*sign, math.MinInt32, math.MaxInt32)
}
func Convert(s string) int {
return myAtoi(s)
}