Skip to content

Commit 47f50e9

Browse files
committed
basic_calculator/
1 parent 246b884 commit 47f50e9

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
180180
#### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square)
181181
#### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes)
182182
#### [223. Rectangle Area](https://github.com/hitzzc/go-leetcode/tree/master/rectangle_area)
183+
#### [224. Basic Calculator](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator)
183184

184185

185186

basic_calculator/basic_calculator.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package basic_calculator
2+
3+
func calculate(s string) int {
4+
ret := 0
5+
stack := []int{}
6+
sign := 1
7+
for i := 0; i < len(s); i++ {
8+
if s[i] >= '0' && s[i] <= '9' {
9+
num := 0
10+
for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ {
11+
num = 10*num + int(s[i]-'0')
12+
}
13+
ret += sign * num
14+
i--
15+
} else if s[i] == '+' {
16+
sign = 1
17+
} else if s[i] == '-' {
18+
sign = -1
19+
} else if s[i] == '(' {
20+
stack = append(stack, ret, sign)
21+
ret = 0
22+
sign = 1
23+
} else if s[i] == ')' {
24+
signTmp := stack[len(stack)-1]
25+
retTmp := stack[len(stack)-2]
26+
stack = stack[:len(stack)-2]
27+
ret = signTmp*ret + retTmp
28+
sign = 1
29+
}
30+
}
31+
return ret
32+
}

0 commit comments

Comments
 (0)