此题没有了中括号和大括号,难度降低,但是负数不要忘记考虑。
public class Main{
public static void main(String[] args){ Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
List<String> arr = new ArrayList<>();
StringBuffer sb= new StringBuffer();;
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(Character.isDigit(ch)){
sb.append(ch);
if(i==str.length()-1 || i<str.length()-1 && !Character.isDigit(str.charAt(i+1))){
arr.add(sb.toString());
sb.setLength(0);
}
}
else if(ch=='-'&&(i==0 || str.charAt(i-1)=='(')){
sb.append(ch);
}
else {
sb.append(ch);
arr.add(sb.toString());
sb.setLength(0);
}
}
List<String> ans = truns(arr);
// for(int i=0;i<ans.size();i++){
// System.out.println(ans.get(i));
// }
int res = cal(ans);
System.out.println(res);
}
public static boolean isD(String str){
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(i==0 && ch=='-'&& str.length()>1){
continue;
}
if(!Character.isDigit(ch)){
return false;
}
}
return true;
}
public static int getLv(String str){
if("+".equals(str)||"-".equals(str)){
return 1;
}
else if("*".equals(str)||"/".equals(str)){
return 2;
}
return -1;
}
public static List<String> truns(List<String> arr){
List<String> ans = new ArrayList<>();
List<String> stack = new ArrayList<>();
int top = -1;
for(int i=0;i<arr.size();i++){
String str = arr.get(i);
if(isD(str)){
ans.add(str);
}
else{
if(top==-1||"(".equals(str)){
stack.add(str);
top++;
}
else if(getLv(str)>getLv(stack.get(top))){
stack.add(str);
top++;
}
else if(")".equals(str)){
while(!"(".equals(stack.get(top))){
ans.add(stack.get(top));
stack.remove(top);
top--;
}
stack.remove(top);
top--;
}
else{
while(top!=-1 && getLv(str)<=getLv(stack.get(top))){
ans.add(stack.get(top));
stack.remove(top);
top--;
}
stack.add(str);
top++;
}
}
}
while(top != -1){
ans.add(stack.get(top));
top--;
}
return ans;
}
public static int cal(List<String> ans){
int res = 0;
List<Integer> stack = new ArrayList<>();
int top = -1;
for(int i=0;i<ans.size();i++){
if(isD(ans.get(i))){
stack.add(Integer.parseInt(ans.get(i)));
top++;
}
else if("+".equals(ans.get(i))){
res = stack.get(top-1) + stack.get(top);
stack.remove(top);
top--;
stack.set(top, res);
}
else if("-".equals(ans.get(i))){
res = stack.get(top-1) - stack.get(top);
stack.remove(top);
top--;
stack.set(top, res);
}
else if("*".equals(ans.get(i))){
res = stack.get(top-1) * stack.get(top);
stack.remove(top);
top--;
stack.set(top, res);
}
else if("/".equals(ans.get(i))){
res = stack.get(top-1) / stack.get(top);
stack.remove(top);
top--;
stack.set(top, res);
}
}
return res;
}
}