-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathN008StringToInt.go
More file actions
80 lines (75 loc) · 1.29 KB
/
N008StringToInt.go
File metadata and controls
80 lines (75 loc) · 1.29 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
type N008StringToInt struct {
}
func (this *N008StringToInt) myAtoi(str string) int32 {
length := len(str)
if length == 0 {
return 0
}
var value int64 = 0
index := 0
indexE := -1
isNeg := false
foundE := false
for str[index] == ' ' && index < length {
index++
}
if str[index] == '-' {
isNeg = true
index++
} else if str[index] == '+' {
index++
}
for ; index < length; index++ {
if str[index] == 'e' || str[index] == 'E' {
foundE = true
indexE = index
break
} else if str[index] >= '0' && str[index] <= '9' {
value = value*10 + int64(str[index]) - int64('0')
if !isNeg {
if value > INT_MAX {
return INT_MAX
}
} else {
if -value < INT_MIN {
return INT_MIN
}
}
} else {
break
}
}
var valueAfterE int64 = 0
if foundE {
for indexE = indexE + 1; indexE < length; indexE++ {
valueAfterE = valueAfterE*10 + int64(str[indexE]) - int64('0')
}
}
oldValue := value
var i int64 = 0
for ; i < valueAfterE; i++ {
value *= 10
if !isNeg {
if value > INT_MAX {
value = oldValue
break
}
} else {
if -value < INT_MIN {
value = oldValue
break
}
}
}
if isNeg {
value = -value
}
if value > INT_MAX {
value = INT_MAX
}
if value < INT_MIN {
value = INT_MIN
}
return int32(value)
}