forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_calculator.go
56 lines (46 loc) · 1.06 KB
/
basic_calculator.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
package stack
import (
"errors"
)
type evaluation struct {
stack []float64
}
// ErrImbalancedParentheses occurs when the expression has imbalanced parentheses.
var ErrImbalancedParentheses = errors.New("expression has imbalanced parentheses")
// BasicCalculator solves the problem in O(n) time and O(n) space.
func BasicCalculator(input string) (float64, error) {
if IsExpressionBalanced(input) {
return -1, ErrImbalancedParentheses
}
return EvaluatePostfixExpression(InfixToPostfix(toInfix(input)))
}
func toInfix(input string) []string {
var (
curNum string
infix []string
)
for _, r := range input {
char := string(r)
if _, ok := operands[char]; ok {
if len(curNum) > 0 {
infix = append(infix, curNum)
curNum = ""
}
infix = append(infix, char)
continue
}
if char == openParenthesis || char == closeParenthesis {
if len(curNum) > 0 {
infix = append(infix, curNum)
curNum = ""
}
infix = append(infix, char)
continue
}
curNum += char
}
if len(curNum) > 0 {
infix = append(infix, curNum)
}
return infix
}