Evaluate Postfix
Completed
Evaluate a postfix expression of single-digit numbers and + - * / (no spaces), e.g. 23*5+. Use an int stack. Print the result.
Input
One expression.
Output
The result (integer division).
Example
Input
23*5+
Output
11
Editor
C
Hints
Digits are pushed; an operator pops two values (the second popped is the left operand).
Solution explanation
Postfix needs no parentheses or precedence rules - a stack evaluates it left to right.
Show solution
#include <stdio.h>
int main() {
char e[100];
int stack[100], top = 0;
scanf("%s", e);
for (int i = 0; e[i] != '\0'; i++) {
char c = e[i];
if (c >= '0' && c <= '9') {
stack[top] = c - '0';
top++;
} else {
int b = stack[top - 1];
int a = stack[top - 2];
top -= 2;
int r;
if (c == '+') r = a + b;
else if (c == '-') r = a - b;
else if (c == '*') r = a * b;
else r = a / b;
stack[top] = r;
top++;
}
}
printf("%d\n", stack[0]);
return 0;
}