2025-01-13 用栈实现计算器-优化(多位数计算)

This commit is contained in:
liangjinglin 2025-01-14 00:42:31 +08:00
parent 6c51073f51
commit bba8bce10f

View File

@ -19,11 +19,12 @@ public class CalculatorByStack {
public void calculate(String expression) {
int length = expression.length();
String numStr = "";
for (int i = 0; i<length;i++){
String str = expression.substring(i,i+1);
String operRegex = "[+\\-*/]";
Pattern operPattern = Pattern.compile(operRegex);
if (operPattern.matcher(String.valueOf(str)).matches()) {
if (operPattern.matcher(str).matches()) {
if("+".equals(str)){
if(operStack.isEmpty()){
operStack.push(ADD);
@ -57,8 +58,15 @@ public class CalculatorByStack {
operStack.push(DIV);
}
}else {
int num = Integer.parseInt(str);
numStack.push(num);
numStr += str;
if (i == expression.length()-1){
numStack.push(Integer.parseInt(numStr));
continue;
}
if (operPattern.matcher(expression.substring(i+1,i+2)).matches()){
numStack.push(Integer.parseInt(numStr));
numStr = "";
}
}
}