Basic Calculator
2015-09-27 20:58
197 查看
题意:
写一个简单的计算器,此计算器只有加法,减法及括号操作
分析:
开两个栈,一个村操作数,一个村操作符,其中+与-同级,当一个操作符要进栈时,判断操作符栈顶元素,若是同级,则让操作数栈出栈两个数,操作符栈出栈栈顶元素,然后将计算出的结果存入操作数栈,待进栈操作符进栈;当遇到左括号时,果断进栈,遇到右括号,则先计算括号中的结果,然后对应的左括号出栈;
最终使得操作符栈为空,计算出的结果即为最后结果
参考代码:
http://www.programcreek.com/2014/06/leetcode-basic-calculator-java/
写好长啊!!!
写一个简单的计算器,此计算器只有加法,减法及括号操作
分析:
开两个栈,一个村操作数,一个村操作符,其中+与-同级,当一个操作符要进栈时,判断操作符栈顶元素,若是同级,则让操作数栈出栈两个数,操作符栈出栈栈顶元素,然后将计算出的结果存入操作数栈,待进栈操作符进栈;当遇到左括号时,果断进栈,遇到右括号,则先计算括号中的结果,然后对应的左括号出栈;
最终使得操作符栈为空,计算出的结果即为最后结果
参考代码:
http://www.programcreek.com/2014/06/leetcode-basic-calculator-java/
写好长啊!!!
public class Solution { public int calculate(String s) { // delte white spaces s = s.replaceAll(" ", ""); Stack<String> stack = new Stack<String>(); char[] arr = s.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (arr[i] == ' ') continue; if (arr[i] >= '0' && arr[i] <= '9') { sb.append(arr[i]); if (i == arr.length - 1) { stack.push(sb.toString()); } } else { if (sb.length() > 0) { stack.push(sb.toString()); sb = new StringBuilder(); } if (arr[i] != ')') { stack.push(new String(new char[] { arr[i] })); } else { // when meet ')', pop and calculate ArrayList<String> t = new ArrayList<String>(); while (!stack.isEmpty()) { String top = stack.pop(); if (top.equals("(")) { break; } else { t.add(0, top); } } int temp = 0; if (t.size() == 1) { temp = Integer.valueOf(t.get(0)); } else { for (int j = t.size() - 1; j > 0; j = j - 2) { if (t.get(j - 1).equals("-")) { temp += 0 - Integer.valueOf(t.get(j)); } else { temp += Integer.valueOf(t.get(j)); } } temp += Integer.valueOf(t.get(0)); } stack.push(String.valueOf(temp)); } } } ArrayList<String> t = new ArrayList<String>(); while (!stack.isEmpty()) { String elem = stack.pop(); t.add(0, elem); } int temp = 0; for (int i = t.size() - 1; i > 0; i = i - 2) { if (t.get(i - 1).equals("-")) { temp += 0 - Integer.valueOf(t.get(i)); } else { temp += Integer.valueOf(t.get(i)); } } temp += Integer.valueOf(t.get(0)); return temp; } }
相关文章推荐
- OCP-V13-008
- 两种方法实现stm32的8个串口通信
- jsonp的工作原理
- ASP.NET WebAPI 05 参数绑定
- HTML使用canvas载入图片
- 三个水杯 21 (bfs 转化) 好题
- 编译lamp
- 关于测试方法以及测试用例设计的一些总结
- HDU 5493 Queue (合肥网络赛 1010 )
- POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
- 从面向过程到面向对象
- C语言宏定义使用技巧
- OCP-V12-007
- leetCode 99: Recover Binary Search Tree
- 如何学好C语言
- C++ string 类常用函数
- 【bzoj3483】【SGU505】【Prefixes and suffixes】【字符串hash】
- 小车电机驱动及相关电路设计
- OCP-V13-006
- HDU 5219 Repeating 后缀数组 + 莫比乌斯函数