Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4217bc2

Browse files
author
hj.tian
committed
feat: add leetcode75 day33 227
feat: add leetcode75 day33 227
1 parent 4dbf4ca commit 4217bc2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎leetcode75/day33_227.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
def calculate(self, s: str) -> int:
3+
"""
4+
stack: 最后只保留需要相加的数字
5+
*: stack[-1] * num
6+
/: stack[-1] // num
7+
-: -num
8+
+: num
9+
return sum(stack)
10+
"""
11+
stack = []
12+
s = s.strip()
13+
num = 0
14+
pre_sign = "+"
15+
for i in range(len(s)):
16+
if s[i].isdigit():
17+
num = num * 10 + int(s[i])
18+
if s[i] in "+-*/" or i == len(s) - 1:
19+
if pre_sign == "+":
20+
stack.append(num)
21+
elif pre_sign == "-":
22+
stack.append(-num)
23+
elif pre_sign == "*":
24+
stack[-1] = stack[-1] * num
25+
elif pre_sign == "/":
26+
# note! -3 // 2 == -2, 所以对负数需要转成正数处理后再变成负数
27+
stack[-1] = stack[-1] // num if stack[-1] > 0 else -((-stack[-1]) // num)
28+
num = 0
29+
pre_sign = s[i]
30+
return sum(stack)
31+
32+
33+
if __name__ == "__main__":
34+
assert Solution().calculate(s="3+2*2") == 7
35+
assert Solution().calculate(s=" 3/2 ") == 1
36+
assert Solution().calculate(s=" 3+5 / 2 ") == 5
37+
assert Solution().calculate(s="14-3/2") == 13

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /