package question;import java.util.ArrayDeque;import java.util.Deque;import java.util.LinkedList;import java.util.Stack;import java.util.concurrent.ArrayBlockingQueue;/*** @author Roderland* @since 1.0*/public class Question227 {public static void main(String[] args) {System.out.println(new Question227().calculate("1*2-3/4+5*6-7*8+9/10"));}public int calculate(String s) {char[] chars = s.toCharArray();Deque<Entity> stack = new LinkedList<>();for (char c : chars) {if (c==' ') continue;if (c=='+') stack.addLast(new Entity(1, 0));else if (c=='-') stack.addLast(new Entity(2, 0));else if (c=='*') stack.addLast(new Entity(3, 0));else if (c=='/') stack.addLast(new Entity(4, 0));else {if (stack.isEmpty()) {stack.addLast(new Entity(0, c-'0'));} else {Entity peek = stack.peekLast();if (peek.type==0) {int value = stack.pollLast().value;if (value>=0) stack.addLast(new Entity(0, peek.value*10+(c-'0')));else stack.addLast(new Entity(0, peek.value*10-(c-'0')));} else if (peek.type==1) {stack.addLast(new Entity(0, c-'0'));} else if (peek.type==2) {stack.pollLast();stack.addLast(new Entity(0, -(c-'0')));} else if (peek.type==3) {stack.addLast(new Entity(0, c-'0'));// stack.pop();// stack.push(new Entity(0, stack.pop().value*(c-'0')));} else if (peek.type==4) {stack.addLast(new Entity(0, c-'0'));// stack.pop();// stack.push(new Entity(0, stack.pop().value/(c-'0')));}}}}Deque<Entity> reStack = new LinkedList<>();while (!stack.isEmpty()) {Entity entity = stack.removeFirst();if (entity.type==3) {reStack.addLast(new Entity(0, reStack.removeLast().value*stack.removeFirst().value));} else if (entity.type==4) {reStack.addLast(new Entity(0, reStack.removeLast().value/stack.removeFirst().value));} else {reStack.addLast(entity);}}int res = 0;while (!reStack.isEmpty()) {Entity entity = reStack.removeFirst();if (entity.type==0) res+=entity.value;}return res;}static class Entity {// 数字:0;加号:1;减号:2;乘号:3;除号:4;int type;int value;public Entity(int type, int value) {this.type = type;this.value = value;}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。