generated from nighthawkcoders/student_2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
public class PrefixCalculator {
// Evaluate prefix
public static int evaluatePrefix(String expression) {
// Store the operands
Stack<Integer> stack = new Stack<>();
// Right to left
for (int i = expression.length() - 1; i >= 0; i--) {
char currentChar = expression.charAt(i);
// Push digits into stack
if (Character.isDigit(currentChar)) {
stack.push(currentChar - '0'); // Convert char to int
}
// Pop operands
else if (isOperator(currentChar)) {
int operand1 = stack.pop();
int operand2 = stack.pop();
// Apply the operator and push the result back to the stack
switch (currentChar) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(operand1 / operand2);
break;
}
}
}
// The result is only element still in stack
return stack.pop();
}
// Check if character valid
public static boolean isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
public static void main(String[] args) {
// Example inputs
String expression1 = "*35";
String expression2 = "*2-75";
// Evaluate expressions and print results
System.out.println("Result of *35: " + evaluatePrefix(expression1));
System.out.println("Result of *2-75: " + evaluatePrefix(expression2));
}
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels