Untitled
unknown
java
3 years ago
2.5 kB
8
Indexable
public static double evaluate(String expression) {
Deque<Double> operands = new ArrayDeque<>();
Deque<Character> operators = new ArrayDeque<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
// Parse the number and push it to the operand stack
int j = i;
while (j < expression.length() && (Character.isDigit(expression.charAt(j)) || expression.charAt(j) == '.')) {
j++;
}
double num = Double.parseDouble(expression.substring(i, j));
operands.push(num);
i = j - 1;
} else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(') {
// Push the operator to the operator stack
operators.push(c);
} else if (c == ')') {
// Pop operators and operands until we reach the matching '('
while (!operators.isEmpty() && operators.peek() != '(') {
char op = operators.pop();
double b = operands.pop();
double a = operands.pop();
double result = applyOperator( a, b, op);
operands.push(result);
}
if (!operators.isEmpty() && operators.peek() == '(') {
operators.pop(); // Discard the '('
}
} else if (c == ' ') {
// Ignore whitespace
} else {
throw new IllegalArgumentException("Invalid operator: " + c);
}
// Check if we need to perform multiplication
if (i < expression.length() - 1 && (c == ')' || Character.isDigit(c)) && (expression.charAt(i + 1) == '(' || expression.charAt(i + 1) == '.' || Character.isDigit(expression.charAt(i + 1)))) {
// We need to perform multiplication, so push a '*' operator to the operator stack
operators.push('*');
}
}
// Perform any remaining operations
while (!operators.isEmpty()) {
char op = operators.pop();
double b = operands.pop();
double a = operands.pop();
double result = applyOperator( a, b, op);
operands.push(result);
}
return operands.pop();
}Editor is loading...