Skip to content

Calculator Enactment HW #17

@eshaank1

Description

@eshaank1

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));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions