-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.go
64 lines (54 loc) · 850 Bytes
/
solution.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
package myatoi
func myAtoi(str string) int {
var start int = -1
var num int = 1
var pos int = 1
force := false
// find the index where is started to be a number
for i := 0; i < len(str); i++ {
c := int(str[i]) - 48
if c >= 0 && c <= 9 {
start = i + 1
num *= c
break
} else {
if force {
return 0
}
switch str[i] {
case ' ':
continue
case '-':
num = -1
pos = -1
force = true
case '+':
force = true
default:
return 0
}
}
}
if start == -1 {
return 0
}
// parse number
for i := start; i < len(str); i++ {
c := int(str[i]) - 48
if c >= 0 && c <= 9 {
num = num*10 + c*pos
if pos > 0 {
if num > 2147483647 {
return 2147483647
}
} else {
if num < -2147483648 {
return -2147483648
}
}
} else {
break
}
}
return num
}