-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-calculator.go
More file actions
107 lines (98 loc) · 1.67 KB
/
basic-calculator.go
File metadata and controls
107 lines (98 loc) · 1.67 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
107
package main
import (
"fmt"
"strconv"
"strings"
)
// source: https://leetcode.com/problems/basic-calculator/
func atoi(x string) int {
y, _ := strconv.ParseInt(x, 10, 32)
return int(y)
}
func calculate(s string) int {
s = strings.ReplaceAll(s, " ", "")
stack := make([]bool, 0)
push := func(x bool) {
stack = append(stack, x)
}
pop := func() bool {
n := len(stack)
x := stack[n-1]
stack = stack[:n-1]
return x
}
top := func() bool {
return stack[len(stack)-1]
}
push(true)
sb := strings.Builder{}
for i, r := range s {
switch r {
case '(':
if i > 0 && s[i-1] == '-' {
push(!top())
} else {
push(top())
}
case ')':
pop()
case '-':
if top() {
sb.WriteString(" -")
} else {
sb.WriteByte(' ')
}
case '+':
if !top() {
sb.WriteString(" -")
} else {
sb.WriteByte(' ')
}
default:
sb.WriteRune(r)
}
}
res := 0
for _, x := range strings.Split(sb.String(), " ") {
res += atoi(x)
}
return res
}
func main() {
testCases := []struct {
s string
want int
}{
{
s: "1 + 1",
want: 2,
},
{
s: " 2-1 + 2 ",
want: 3,
},
{
s: "(1+(4+5+2)-3)+(6+8)",
want: 23,
},
{
s: "-(4-5-(7+(91+3-(17+4))))",
want: 81,
},
}
successes := 0
for _, tc := range testCases {
x := calculate(tc.s)
status := "ERROR"
if fmt.Sprint(x) == fmt.Sprint(tc.want) {
status = "OK"
successes++
}
fmt.Println(status, " Expected: ", tc.want, " Actual: ", x)
}
if l := len(testCases); successes == len(testCases) {
fmt.Printf("===\nSUCCESS: %d of %d tests ended successfully\n", successes, l)
} else {
fmt.Printf("===\nFAIL: %d tests failed\n", l-successes)
}
}