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.
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.
