-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrdp_expr.go
84 lines (76 loc) · 986 Bytes
/
rdp_expr.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
package main
import (
"bufio"
"fmt"
"os"
)
type symbol struct {
c byte
val int
}
var sym symbol
var reader *bufio.Reader
func next() {
c, err := reader.ReadByte()
if err != nil {
return
}
if c == ' ' {
next()
return
}
if c >= '0' && c <= '9' {
reader.UnreadByte()
fmt.Fscanf(reader, "%d", &sym.val)
sym.c = 0
return
}
sym.c = c
}
func factor() int {
if sym.c == '(' {
v := exp()
if sym.c != ')' {
panic("mismatched parentheses")
}
next()
return v
}
next()
return sym.val
}
func term() int {
v1 := factor()
for sym.c == '*' || sym.c == '/' {
op := sym.c
next()
v2 := factor()
switch op {
case '*':
v1 *= v2
case '/':
v1 /= v2
}
}
return v1
}
func exp() int {
next()
v1 := term()
for sym.c == '+' || sym.c == '-' {
op := sym.c
next()
v2 := term()
switch op {
case '+':
v1 += v2
case '-':
v1 -= v2
}
}
return v1
}
func main() {
reader = bufio.NewReader(os.Stdin)
fmt.Println(exp())
}