给定一个包含正整数,加法(+),减法(-),乘法(*),除法(/)的算术表达式(括号除外),计算其结果,表达式仅包含非负整数,+,-,*,/四种运算符和空格。整数除法仅包含整数部分
示例1:
输入:“3+3*2”
输出 : 7
输入:“3/2”
输出:1
此算法利用栈来实现,一个栈用来存储数字,另一个栈用来存储表达式字符,逻辑1.数字直接入数字栈,2,运算符c >栈顶运算符 c直接入栈 3.运算符c <=栈顶运算符 栈顶出栈计算
代码:
package 算法.栈;
import java.util.Scanner;
import java.util.Stack;
public class 计算器 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int result = calculate(str);
System.out.println(result);
}
private static int calculate(String str) {
Stack<Integer> nums = new Stack<>(); // 存放数字
Stack<Character> ops = new Stack<>(); // 存放运算符
int i = 0;
int n = str.length();
while (i < n) {
char c = str.charAt(i);
if (c == ' ') { // 跳过空格
i++;
} else if (isDigit(c)) { // 如果为数字
int num = 0;
while (i < n && isDigit(str.charAt(i))) {
num = num * 10 + str.charAt(i) - '0';
i++;
}
nums.push(num);
} else { // 运算符
if (ops.isEmpty() || prior(c, ops.peek())) { // 比较运算符等级
ops.push(c);
} else {
while (!ops.isEmpty() && !prior(c, ops.peek())) {
fetchAndCal(nums, ops);
}
ops.push(c);
}
i++;
}
}
while (!ops.isEmpty()) { // 最后检查计算栈内剩余的字符和数字
fetchAndCal(nums, ops);
}
return nums.pop();
}
public static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
public static boolean prior(char a, char b) {
if ((a == '*' || a == '/') && (b == '+' || b == '-')) {
return true;
} else {
return false;
}
}
public static void fetchAndCal(Stack<Integer> nums, Stack<Character> ops) {
int num2 = nums.pop();
int num1 = nums.pop();
char op = ops.pop();
int res = 0;
switch (op) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
}
nums.push(res);
}
}