-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicCalculator.py
More file actions
32 lines (30 loc) · 849 Bytes
/
basicCalculator.py
File metadata and controls
32 lines (30 loc) · 849 Bytes
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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/basic-calculator/
# Author: Miao Zhang
# Date: 2021-01-27
class Solution:
def calculate(self, s: str) -> int:
res = 0
num = 0
sign = 1
stack = []
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == "+" or c == "-":
res += sign * num
num = 0
sign = 1 if c == "+" else -1
elif c == "(":
stack.append(res)
stack.append(sign)
res = 0
sign = 1
elif c == ")":
res += sign * num
num = 0
res *= stack.pop()
res += stack.pop()
res += sign * num
return res