End of Year Sale: Use Coupon Code END2025 to Get Extra 25% Off.
09DAYS
:
00HOURS
:
28MINUTES
:
08SECONDS
Leetcode Problem 227. Basic Calculator II
227. Basic Calculator II
Leetcode Solutions
Using Stack to Evaluate Expressions
Initialize a stack to store numbers.
Initialize variables for the current number and the last operator to '+' (as the first number is always added).
Iterate over the string, handling spaces, numbers, and operators.
If the character is a number, parse it and update the current number.
If the character is an operator or the end of the string is reached:
a. If the last operator is '+', push the current number onto the stack.
b. If the last operator is '-', push the negative of the current number onto the stack.
c. If the last operator is '*', pop from the stack, multiply with the current number, and push the result back onto the stack.
d. If the last operator is '/', pop from the stack, divide by the current number, and push the result back onto the stack.
Update the last operator to the current operator.
Reset the current number to 0.
After the iteration, pop all numbers from the stack, sum them up, and return the sum as the result.