题目链接
题解
所谓后缀表达式式,即为逆波兰式,此题用栈做
栈的特点:先进后出,逆波兰式的计算就是即后缀表达式,其计算方法和栈的特点不谋而合!!!
题解如下:
package com.company;
import java.util.Scanner;
import java.util.Stack;
/**
* @Author 小GUI渡江
* @Date 2022/4/6 21:24
**/
public class nibolansi_6 {
//创建栈
static Stack<Integer> stack = new Stack<>();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = new String();
str = scan.nextLine();
int sum = 0;
boolean flag = false;
int num = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '@') {
break;
}else if(str.charAt(i) >= '0' && str.charAt(i) <= '9' || str.charAt(i) == '.') {
//判断是否是数字或断点
if(!flag) {
num = i;
flag = true;
continue;
}else if(str.charAt(i) == '.') {
stack.push(Integer.parseInt(str.substring(num, i)));
num = 0;
flag = false;
continue;
}
}else {
//需要注意a和b,a是后进栈的,在减法和除法的时候,需要注意a和b的前后位置
int a = stack.pop();
int b = stack.pop();
if(str.charAt(i) == '+') {
sum = b + a;
}else if(str.charAt(i) == '-') {
sum = b - a;
}
else if(str.charAt(i) == '/') {
sum = b / a;
}else if(str.charAt(i) == '*') {
sum = b * a;
}
stack.push(sum);
}
}
System.out.print(stack.pop());
}
}