Basic Calculator
2015-09-26 04:40
302 查看
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
the plus
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
The expression string may contain open
(and closing parentheses
),
the plus
+or minus sign
-, non-negative integers
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
public class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<Integer>(); int result = 0; int number = 0; int sign = 1; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(Character.isDigit(c)){ number = 10 * number + (int)(c - '0'); }else if(c == '+'){ result += sign * number; number = 0; sign = 1; }else if(c == '-'){ result += sign * number; number = 0; sign = -1; }else if(c == '('){ //we push the result first, then sign; stack.push(result); stack.push(sign); //reset the sign and result for the value in the parenthesis sign = 1; result = 0; }else if(c == ')'){ result += sign * number; number = 0; result *= stack.pop(); //stack.pop() is the sign before the parenthesis result += stack.pop(); //stack.pop() now is the result calculated before the parenthesis } } if(number != 0) result += sign * number; return result; } }
相关文章推荐
- Python已安装第三方库
- LeetCode Spiral Matrix II
- 算法导论第七章快速排序
- 从0开始学angularjs-笔记04
- java Synchronized一些列问题解答
- Python安装cx_Oracle第三方库(Mac osx Yosemite Intel i5环境)
- Android入门——Service详解及应用(一)
- 接口的行为抽象和抽象类的行为抽象
- eclipse 配置c++开发环境
- Windows 10开发基础——文件、文件夹和库(一)
- 关于无刷新实现文件上传
- Android Studio 更换debug.keystore问题
- LeetCode Spiral Matrix
- Basic Calculator II
- java1.5连接oracle12c
- 野指针(随便写写)
- 关于HTML5的拖拽
- linux运维实战练习及linux shell脚本、awk、sed工具命令学习总结
- IOS 开发笔记——使用类型常量,少用预处理命令
- 工作的感悟