package wordcount.算数表达式;
public class MathExpression {
static String[] str={"(","(","2","+","3",")",")","*","(","5","+","7",")","+","9","/","3"};
static int index=0;
public static void main(String[] args){
System.out.println(add());
}
static Double add(){
Double target = mul();
while (index<str.length){
if(str[index].equals("+")){
++index;
double mv=mul();
target+=mv;
}
else if(str[index].equals("-")){
++index;
double mv=mul();
target=target-mv;
}
else{
break;
}
}
return target;
}
static Double mul(){
Double target = expr();
while (index<str.length){
if(str[index].equals("*")){
++index;
double mv=expr();
target=target*mv;
}
else if(str[index].equals("/")){
++index;
double mv=expr();
target=target/mv;
}
else{
break;
}
}
return target;
}
private static Double expr() {
if(str[index].equals("(")){
++index;
Double add = add();
++index;
return add;
}
double x=Double.parseDouble(str[index]);
++index;
return x;
}
}
//优先级 expr>mul>add
On复杂度递归求算数表达式
最新推荐文章于 2024-06-16 18:08:27 发布