package Leecode;
import java.util.ArrayDeque;
import java.util.Deque;
public class Calculator {
public static double calculate(String s) {
int n = s.length();
if (n == 0) return 0;
double temp = 0;
double result = 0;
Character sign = '+';
Deque<Double> deque = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
//小数点
if (s.charAt(i) == '.') {
int j = i + 1;
double temp1 = 0;
while (j < n && Character.isDigit(s.charAt(j))) {
temp1 = temp1 * 10 + s.charAt(j) - '0';
//System.out.println(temp1);
j++;
}
int length = j - i - 1;
temp = temp + temp1 / Math.pow(10, length);
//System.out.println(temp);
if (j != n) i = j;
else {
i = j - 1;
if (sign == '+') {
deque.push(temp);
} else if (sign == '-') {
deque.push(-temp);
} else if (sign == '*') {
deque.push(deque.pop() * temp);
} else if (sign == '/') {
deque.push(deque.pop() / temp);
}
break;
}
}
if (i < n && Character.isDigit(s.charAt(i))) {
temp = temp * 10 + s.charAt(i) - '0';
}
//考虑运算一个负数 如2*-2.5,这时候的-就不能看成运算符
if (i<n-1&&i>0&&s.charAt(i)=='-' &&!Character.isDigit(s.charAt(i-1))){
int j =i+1;
double temp1 = 0;
while (j < n && (Character.isDigit(s.charAt(j))||s.charAt(j)=='.')) {
while (j<n&&Character.isDigit(s.charAt(j))) {
temp1 = temp1 * 10 + s.charAt(j) - '0';
j++;
}
//System.out.println(temp1);
if (j<n-1&&s.charAt(j)=='.'){
int k = j + 1;
double temp2 = 0;
while (k < n && Character.isDigit(s.charAt(k))) {
temp2 = temp2 * 10 + s.charAt(k) - '0';
//System.out.println(temp1);
k++;
}
int length = k-j-1;
temp1 = temp1 + temp2/Math.pow(10,length);
//System.out.println(temp1);
j = k;
}
}
temp = -temp1;
i = j-1;
}
//运算符
if (i < n && (!Character.isDigit(s.charAt(i))) || i == n - 1) {
//System.out.println(sign);
if (sign == '+') {
deque.push(temp);
} else if (sign == '-') {
deque.push(-temp);
} else if (sign == '*') {
deque.push(deque.pop() * temp);
} else if (sign == '/') {
deque.push(deque.pop() / temp);
}
sign = s.charAt(i);
temp = 0;
}
}
//加起来的得数
while (!deque.isEmpty()) {
//System.out.println(deque.peek());
result += deque.pop();
}
return result;
}
}
测试结果:
image.png
image.png
健壮性也很强,可以加负数
image.png
image.png









网友评论