AcWing 151. Java看我
原题链接
中等
作者:
Zh1995
,
2020-08-14 16:08:05
,
所有人可见
,
阅读 549
import java.util.*;
class Main{
static LinkedList<Integer> nums=new LinkedList<>();
static LinkedList<Character> ops=new LinkedList<>();
static HashMap<Character,Integer> map=new HashMap<>();
static void cal(){
int b=nums.pollLast();
int a=nums.pollLast();
char c=ops.pollLast();
if(c=='+') nums.addLast(a+b);
if(c=='-') nums.addLast(a-b);
if(c=='*') nums.addLast(a*b);
if(c=='/') nums.addLast(a/b);
if(c=='^') nums.addLast((int)Math.pow(a,b));
}
public static void main(String args[]){
map.put('+',1); map.put('-',1); map.put('*',2); map.put('/',2); map.put('^',3);
Scanner sc=new Scanner(System.in);
String str=sc.next();
StringBuffer sb=new StringBuffer();
for(int i=0;i<str.length();i++) sb.append('(');
str=sb.toString()+str+')';
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if(c<='9' && c>='0'){
int val=0,j=i;
while(j<str.length() && str.charAt(j)<='9' && str.charAt(j)>='0')
val=val*10+(str.charAt(j++)-'0');
nums.addLast(val);
i=j-1;
}
else if(c=='(') ops.addLast(c);
else if(c==')'){
while(ops.peekLast()!='(') cal();
ops.pollLast();
}
else if(c=='-'){
if((i!=0 && (str.charAt(i-1)<'0' || str.charAt(i-1)>'9')) && (i!=0 && str.charAt(i-1)!=')')){
int val=0,j=i+1;
while(j<str.length() && str.charAt(j)<='9' && str.charAt(j)>='0')
val=val*10+(str.charAt(j++)-'0');
nums.addLast(-val);
i=j-1;
}
else{
while(ops.peekLast()!='(') cal();
ops.addLast(c);
}
}
else{
while(!ops.isEmpty() && ops.peekLast()!='(' && map.get(ops.peekLast())>=map.get(c)) cal();
ops.addLast(c);
}
}
System.out.println(nums.pollLast());
}
}