-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathatoi.go
66 lines (60 loc) · 1.03 KB
/
atoi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import "fmt"
func myAtoi(str string) int {
for len(str) > 0 && str[0] == ' ' {
str = str[1:]
}
if len(str) == 0 {
return 0
}
negtive := false
if str[0] == '-' || str[0] == '+' {
if str[0] == '-' {
negtive = true
}
str = str[1:]
}
var ans int32
overflow := false
for i := 0; i < len(str); i++ {
if str[i] >= '0' && str[i] <= '9' {
if ans > 2147483647/10 {
overflow = true
break
}
var digit int32
digit = int32(str[i] - '0')
ans = ans*10 + digit
fmt.Println(digit, ans)
if ans < 0 {
overflow = true
break
}
} else {
break
}
}
if negtive {
ans = -ans
if overflow {
ans = -2147483648
}
return int(ans)
} else {
if overflow {
ans = 2147483647
}
return int(ans)
}
}
func main() {
/*
fmt.Println(myAtoi(""))
fmt.Println(myAtoi("12345aaa"))
fmt.Println(myAtoi("+-2"))
fmt.Println(myAtoi("9223372036854775809"))
*/
//fmt.Println(myAtoi("1095502006p8"))
//fmt.Println(myAtoi("18446744073709551617"))
fmt.Println(myAtoi(" 10522545459"))
}