标签:String int pop parseInt num 求值 stack 表达式
给定一个四则运算(带括号表达式)加减乘除由+ - * /表示,求运算结果
import java.util.Scanner;
import java.util.Stack;
public class Main {
/**
* 将数字放入栈中,如果栈顶有乘除,则结算乘除
*
* @param stack
* @param num
*/
private static void pushNumToStack(Stack<String> stack, int num) {
if (!stack.isEmpty() && "*".equals(stack.peek())) {
stack.pop();
stack.push(String.valueOf(Integer.parseInt(stack.pop()) * num));
} else if (!stack.isEmpty() && "/".equals(stack.peek())) {
stack.pop();
stack.push(String.valueOf(Integer.parseInt(stack.pop()) / num));
} else {
stack.push(String.valueOf(num));
}
}
/**
* 由于将数字放入栈时已经结算乘除,所以此时栈中只有加减
*
* @param stack
* @return
*/
private static int calcStack(Stack<String> stack) {
while (stack.size() >= 3) {
int two = Integer.parseInt(stack.pop());
String op = stack.pop();
int one = Integer.parseInt(stack.pop());
if ("-".equals(op)) {
stack.push(String.valueOf(one - two));
} else {
stack.push(String.valueOf(one + two));
}
}
return Integer.parseInt(stack.pop());
}
private static int[] calc(char[] str, int index) {
Stack<String> stack = new Stack<>();
int num = 0;
while (index < str.length && str[index] != ')') {
if (str[index] >= '0' && str[index] <= '9') {
num = num * 10 + str[index++] - '0';
} else if (str[index] == '(') {
int[] next = calc(str, index + 1);
num = next[0];
index = next[1] + 1;
} else {
pushNumToStack(stack, num);
num = 0;
stack.push(String.valueOf(str[index++]));
}
}
pushNumToStack(stack, num);
return new int[]{calcStack(stack), index};
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.next();
System.out.println(calc(str.toCharArray(), 0)[0]);
}
}
}
标签:String,int,pop,parseInt,num,求值,stack,表达式 来源: https://www.cnblogs.com/tianyiya/p/15411209.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。