实现一个基本的计算器来计算一个简单的字符串表达式。
字符串表达式仅包含非负整数,+, - ,*,/四种运算符和空格 。 整数除法仅保留整数部分。
你可以假定所给定的表达式总是有效的。
一些例子:
“3+2*2” = 7 ” 3/2 ” = 1 ” 3+5 / 2 ” = 5
因为要优先计算乘除,因此可以用栈先存储遍历到的加减运算,先做乘除,做完乘除的结果才放入栈中,最后出栈,因为这时要先从栈底出,因此可以用LinkdedList实现这个结构
public int calculate(String s) {
LinkedList<Object> linkedList = new LinkedList<Object>();
String tempNum = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
tempNum += s.charAt(i);
} else if (s.charAt(i) == ' ' || s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) == '/') {
if (!tempNum.equals("")) {//放进去一个数,放进去之前要看前面是不是乘除法
int tempRes = Integer.parseInt(tempNum);
if (!linkedList.isEmpty() && linkedList.getLast().equals("*")) {
linkedList.removeLast();
tempRes = (Integer) linkedList.removeLast() * tempRes;
} else if (!linkedList.isEmpty() && linkedList.getLast().equals("/")) {
linkedList.removeLast();
tempRes = (Integer) linkedList.removeLast() / tempRes;
}
linkedList.offer(tempRes);
tempNum = "";
}
if (s.charAt(i) != ' ') {//当前是运算符号
linkedList.offer(s.charAt(i) + "");
}
}
}
System.out.println(System.currentTimeMillis());
if (s.charAt(s.length() - 1) != ' ') {//处理最后一个数
int tempRes = Integer.parseInt(tempNum);
if (!linkedList.isEmpty() && linkedList.getLast().equals("*")) {
linkedList.removeLast();
tempRes = (Integer) linkedList.removeLast() * tempRes;
} else if (!linkedList.isEmpty() && linkedList.getLast().equals("/")) {
linkedList.removeLast();
tempRes = (Integer) linkedList.removeLast() / tempRes;
}
linkedList.offer(tempRes);
}
System.out.println(System.currentTimeMillis());
return calculate(linkedList);
}
private int calculate(LinkedList<Object> linkedList) {//纯加减法运算
int res = (Integer) linkedList.removeFirst();
while (!linkedList.isEmpty()) {
if (linkedList.getFirst().equals("+")) {
linkedList.removeFirst();
res += (Integer) linkedList.removeFirst();
} else if (linkedList.getFirst().equals("-")) {
linkedList.removeFirst();
res -= (Integer) linkedList.removeFirst();
}
}
System.out.println(System.currentTimeMillis());
return res;
}