Nlogk
Code Patterns

Basic Calculator

Code Pattern

Get Number

  1. get_number: Reads and converts a sequence of digits from the string into an integer.

Update Stack

  1. update_stack: Modifies the stack based on the arithmetic operation specified, enabling the evaluation of expressions in a structured manner.
    • Addition: If the operator is +, it appends num to the stack.
    • Subtraction: If the operator is -, it appends -num to the stack to account for the negative value.
    • Multiplication: If the operator is *, it pops the top value from the stack, multiplies it by num, and appends the result back to the stack.
    • Division: If the operator is /, it pops the top value, performs integer division with num, and appends the result back to the stack (using int to ensure integer division).

Calculate

  1. Character Processing
    • If the character is a digit, it retrieves the full number.
    • If it encounters a (, it recursively calls calc() to evaluate the expression inside.
    • If it sees a ), it updates the stack with the current num and operator, then returns the sum of the stack.
    • For operators (+, -, *, /), it updates the stack with the current number and operator, sets the new operator, and resets num.
def calculate(self, s: str) -> int:
self.index = 0
def get_number():
num = 0
while self.index < len(s) and s[self.index].isdigit():
num = num * 10 + int(s[self.index])
self.index += 1
return num

Common mistakes

  1. Forget to reset num after an operator
# Wrong: Forgetting to reset num after processing an operator
elif char in '+-*/':
update_stack(stack, num, operator)
# num is not reset here, leading to incorrect calculations
# Correct:
elif char in '+-*/':
update_stack(stack, num, operator)
operator = char
num = 0 # Reset num for the next number

224. Basic Calculator

class Solution:
def calculate(self, s: str) -> int:
self.index = 0
def get_number():
# Use the code above
def update_stack(stack, num, operator):
# Use the code above
def calc():
# Use the code above
return calc()

227. Basic Calculator II

class Solution:
def calculate(self, s: str) -> int:
self.index = 0
def get_number():
# Use the code above
def update_stack(stack, num, operator):
# Use the code above
def calc():
# Use the code above
return calc()

227. Basic Calculator III

class Solution:
def calculate(self, s: str) -> int:
self.index = 0
def get_number():
# Use the code above
def update_stack(stack, num, operator):
# Use the code above
def calc():
# Use the code above
return calc()