package com.zsx.structure.stack;
import java.util.HashMap;
import java.util.Map;
public class SimpleCalculator {
public static Map<Character, Integer> characterMap = new HashMap<>();
static {
SimpleCalculator.characterMap.put('+', 1);
SimpleCalculator.characterMap.put('-', 2);
SimpleCalculator.characterMap.put('*', 3);
SimpleCalculator.characterMap.put('×', 3);
SimpleCalculator.characterMap.put('/', 3);
}
public static void main(String[] args) {
String formula = "1 + 3 - 2 * 2 / 2 + 92/92 - 1 + 5";
Integer result = SimpleCalculator.calcutator(formula);
System.out.println(formula + " = " + result);
}
public static Integer calcutator(String formula) {
Stack<Integer> number = new Stack<>(100);
Stack<Character> character = new Stack<>(100);
for (int i = 0; i < formula.length(); i++) {
char c = formula.charAt(i);
if (Character.isDigit(c)) {
if (!number.isEmpty() && Character.isDigit(formula.charAt(i - 1))) {
Integer last = number.pop();
number.pull(last * 10 + (int) (formula.charAt(i)) - '0');
} else {
number.pull((int) (formula.charAt(i)) - '0');
}
}
else if (characterMap.containsKey(c)) {
if (!character.isEmpty()) {
while (characterMap.get(character.getPop()) > characterMap.get(c)) {
Integer num2 = number.pop();
Integer num1 = number.pop();
Integer res = SimpleCalculator.calcutator(num1, num2, character.pop());
number.pull(res);
}
character.pull(formula.charAt(i));
} else {
character.pull(formula.charAt(i));
}
}
}
while (!character.isEmpty()) {
Integer num2 = number.pop();
Integer num1 = number.pop();
Integer res = SimpleCalculator.calcutator(num1, num2, character.pop());
number.pull(res);
}
return number.getPop();
}
public static Integer calcutator(Integer num1, Integer num2, char charact) {
switch (charact) {
case '×':
case '*':
return num1 * num2;
case '/':
return num1 / num2;
case '+':
return num1 + num2;
case '-':
return num1 - num2;
default:
throw new RuntimeException("符号异常:" + charact);
}
}
}
package com.zsx.structure.stack;
class Stack<T> {
private int maxSize;
private T[] stack;
private int top = -1;
public Stack(int maxSize) {
this.maxSize = maxSize;
stack = (T[]) new Object[maxSize];
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
public void pull(T data) {
if (this.isFull()) {
System.out.println("满了");
return;
}
top++;
stack[top] = data;
}
public T pop() {
if (this.isEmpty()) {
throw new RuntimeException("空");
}
T value = stack[top];
top--;
return value;
}
public T getPop() {
if (this.isEmpty()) {
throw new RuntimeException("空");
}
return stack[top];
}
public void show() {
System.out.println("________________________");
if (!this.isEmpty()) {
for (int i = this.top; i >= 0; i--) {
System.out.println("第" + i + "个:" + this.stack[i]);
}
}
}
}