Repository navigation
Expand file tree
/
Copy pathstrToInt.go
More file actions
106 lines (97 loc) · 1.79 KB
/
Copy pathstrToInt.go
File metadata and controls
106 lines (97 loc) · 1.79 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package randomPick
type Machine struct {
State MState
Symbol int
Result int
Inputs []rune
}
type MState int
const (
Exit MState = iota
Start
Space
Symbol
Number
)
func isSpace(r rune) bool {
return r == ' '
}
func isSymbol(r rune) bool {
return r == '-' || r == '+'
}
func isDiget(r rune) bool {
return int(r) >= '0' && int(r) <= '9'
}
func (machine *Machine) next(r rune) bool {
maxInt := (1 << 31) - 1
maxIntD10 := maxInt / 10
switch machine.State {
case Start, Space:
if isSpace(r) {
machine.State = Space
return true
} else if isSymbol(r) {
machine.State = Symbol
if r == '-' {
machine.Symbol = -1
} else {
machine.Symbol = 1
}
return true
} else if isDiget(r) {
machine.State = Number
machine.Result = machine.Result*10 + int(r) - '0'
return true
} else {
machine.State = Exit
return false
}
case Symbol, Number:
if isDiget(r) {
if machine.Result > maxIntD10 {
if machine.Symbol > 0 {
machine.Result = maxInt
} else {
machine.Result = maxInt + 1
}
}
machine.State = Number
state, res := getProperResult(machine.Result*10+int(r)-'0', machine.Symbol, maxInt)
machine.Result = res
if !state {
machine.State = Exit
return false
}
return true
} else {
machine.State = Exit
return false
}
case Exit:
return false
}
return true
}
func getProperResult(re int, symbol int, max int) (reFlag bool, result int) {
if symbol > 0 && re > max {
return false, max
} else if symbol < 0 && re > max+1 {
return false, max + 1
} else {
return true, re
}
}
func myAtoi(s string) int {
machine := Machine{
State: Start,
Symbol: 1,
Result: 0,
Inputs: []rune(s),
}
for _, r := range machine.Inputs {
if !machine.next(r) {
break
}
}
return machine.Result * machine.Symbol
}