224. Basic Calculator
2016-03-22 10:43
260 查看
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:
Note: Do not use the
library function.
Subscribe to see which companies asked this question
Stack 存起来就行
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
Note: Do not use the
evalbuilt-in
library function.
Subscribe to see which companies asked this question
Stack 存起来就行
public class Solution { private int calc(Stack<String> stack2){ int ret = 0; int state = 1;//1为加0为减 while(!stack2.empty()){ 4000 int num = 0; String tem = stack2.pop(); if(tem.equals(")"))break; else if(tem.equals("("))num=calc(stack2); else if(tem.equals("+")){state=1; continue; } else if(tem.equals("-")){state=0; continue; }else { num=Integer.parseInt(tem); } if(state==1){ ret=ret+num; }else{ ret=ret-num; } } return ret; } public int calculate(String s) { Stack<String> stack=new Stack<>(); Stack<String> stack2 = new Stack<>(); int length = s.length(); for(int i=length-1;i>=0;){ char k = s.charAt(i); if(k==' '){ i--; continue; } if(k==')'||k=='('||k=='+'||k=='-'){ String t = ""+s.charAt(i); i--; stack2.push(t); continue; } String t = ""; while(i>=0&&(s.charAt(i)==' '||('0'<=s.charAt(i)&&'9'>=s.charAt(i)))){ k=s.charAt(i); if(k==' '){ i--; continue; } t = k+t; i--; } stack2.push(t); } return calc(stack2); } }
相关文章推荐
- Html+css+javascript总结
- how to write order by and limit query in jpa [duplicate]
- eclipse 安装svn插件
- 远程连接oracle数据库telnet 1521端口失败
- PHP实现补齐关闭的HTML标签
- 商业智能系统在税务行业的应用
- rotaluclaCcisaB.224
- CSS颜色代码大全
- PagerTabStrip修改选中/未选中tab字体颜色
- 商业智能系统在税务行业的应用
- dhtmlxGrid实现setColumnHidden
- Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]
- 3. Longest Substring Without Repeating Characters
- Finding Deceptive Opinoin Spam by Any Stretch of the Imagination (Myle Ott Yjin Choi)
- tcp短连接场长连接
- HDOJ 2000 ASCII码排序
- mysql的yearweek 和 weekofyear函数
- http://blog.csdn.net/lmj623565791/article/details/50709663
- junit中before和beforeclass,多个test执行顺序
- Android自动化测试(UiAutomator)简要介绍 - 萧瑟一笑的专栏 - 博客频道 - CSDN.NET