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