You are given a string containing a valid arithmetic expression with integers and the operators +, -, *, /. There are no parentheses. Evaluate the expression and return the result.
Operator precedence matters: multiplication and division must be evaluated before addition and subtraction. A stack makes this easy. Iterate through the string, parse numbers, and when you see a + or -, push the number (positive or negative). When you see * or /, pop the last number, compute the result, and push it back. At the end, sum all values on the stack.
Integer division should truncate toward zero. The expression is always valid.Operator precedence makes this problem more complex than a simple left-to-right evaluation. Multiplication and division must be computed before addition and subtraction. The stack handles this by deferring addition and subtraction until all higher-precedence operations are resolved.The sign variable tracks the operator immediately before the current number. When a + or - is encountered, the current number (with its sign) is pushed onto the stack. When * or / is encountered, the last number on the stack is popped, the operation is performed immediately, and the result is pushed back.At the end, the stack contains only positive and negative numbers that can be summed directly. This approach works because multiplication and division are binary operations that produce a single result, while addition and subtraction simply accumulate signed values.Integer division must truncate toward zero. The expression is guaranteed to be valid and will not contain division by zero. Spaces in the input should be ignored.
Example Input & Output
5/2=2, then 3+2=5
2*2=4, then 3+4=7
-5*2=-10, then 3-10=-7, then -7+2=-5
Integer division truncates toward zero: 3/2=1
Algorithm Flow
Solution Approach
Iterate through the string character by character, building the current number. When you encounter an operator or reach the end, check the previous operator. If it was + or -, push the current number (with sign) onto the stack. If it was * or /, pop the last number, compute the result, and push it back. At the end, sum all values on the stack.
Time complexity is O(n). Space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(String s) {
Stack<Integer> stack = new Stack<>();
int num = 0; char sign = '+';
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') num = num * 10 + (ch - '0');
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || i == s.length() - 1) {
if (sign == '+') stack.push(num); else if (sign == '-') stack.push(-num);
else if (sign == '*') stack.push(stack.pop() * num);
else if (sign == '/') stack.push(stack.pop() / num);
num = 0; sign = ch;
}
}
int sum = 0; while (!stack.isEmpty()) sum += stack.pop();
return sum;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
