227. Basic Calculator II
2016-03-31 01:20
363 查看
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
The expression string contains only non-negative integers,
+,
-,
*,
/operators
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
public static int calculate(String s) { s = s.replaceAll("\\s+", ""); int result = 0; int num = 0; int sign = 1; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '+'){ result += num * sign; num = 0; sign = 1; continue; }else if(c == '-'){ result += num *sign; num = 0; sign = -1; continue; }else if(c == '*'){ int num2 = 0; while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){//don't forget the first condition num2 = num2*10 + s.charAt(i + 1) - '0'; i++; } num *= num2; }else if(c == '/'){ int num2 = 0; while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){//don't forget the first condition num2 = num2*10 + s.charAt(i + 1) - '0'; i++; } num /= num2; }else{ num = num*10 + c - '0'; } } if(num != 0){ result += sign * num; } return (int)result; } public static void main(String[] args) { String s = "3+2*2-1"; String s2 = "3/2"; String s3 = " 3+5 / 2 "; String s4 = "1*2*3*4*5*6*7*8*9*10"; String s5 = "100000000/1/2/3/4/5/6/7/8/9/10"; System.out.println(calculate(s5)); }
相关文章推荐
- Qt15 Update a data from Sqlite database with pushbutton
- 流式布局之2012年语法-------------------CSS3盒模型display:flex
- BAT执行PHP文件(区别于上一篇)
- Java字符串详解
- RecyclerView
- Thread详解11:ThreadLocal的使用
- Java并发编程:同步容器
- Callable与Runnable区别
- string 与char* char[]之间的转换
- Unity3d的批渲染 batch rendering(转载,为了方便自己看,记忆的)
- 视频播放(三)——视频播放
- BAT执行PHP
- 做高算踩到的坑
- 不用MWPhotoBrowser,自定制图片浏览器+过场动画代码,超简单!get
- GET,POST — 简述
- LB 负载均衡的层次结构
- LB 负载均衡的层次结构
- LB 负载均衡的层次结构
- linux中,某文件的权限是:drw-r--r--,用数值形式表示该权限,则该八进制数为多少?
- 初识PHP之一个注释埋下的坑!