-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob0227.go
88 lines (77 loc) · 1.33 KB
/
prob0227.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package prob0227
type StackInt struct {
Data []int
}
func (s *StackInt) Top() int {
if len(s.Data) == 0 {
return 0
}
return s.Data[len(s.Data)-1]
}
func (s *StackInt) Push(i int) {
s.Data = append(s.Data, i)
}
func (s *StackInt) Pop() {
if len(s.Data) == 0 {
}
s.Data = s.Data[0 : len(s.Data)-1]
}
func (s *StackInt) IsEmpty() bool {
return len(s.Data) == 0
}
func NewStackInt() *StackInt {
return &StackInt{
Data: []int{},
}
}
func calculate(s string) int {
stack := NewStackInt()
b := []byte(s)
b = tripStr(b)
bLen := len(b)
item, index := getNextIntStr(b)
stack.Push(item)
for index < bLen-1 {
nextItem, nextIndex := getNextIntStr(b[index+1:])
switch b[index] {
case '+':
stack.Push(nextItem)
case '-':
stack.Push(-nextItem)
case '*', '/':
top := stack.Top()
newTop := top * nextItem
if b[index] == '/' {
newTop = top / nextItem
}
stack.Pop()
stack.Push(newTop)
}
index += nextIndex + 1
}
res := 0
for !stack.IsEmpty() {
res += stack.Top()
stack.Pop()
}
return res
}
func tripStr(s []byte) []byte {
new := []byte{}
for _, v := range s {
if v != ' ' {
new = append(new, v)
}
}
return new
}
func getNextIntStr(b []byte) (res, index int) {
for i, v := range b {
index = i
if v < '0' || v > '9' {
break
}
res = res*10 + int(v-'0')
}
return res, index
}