LeetCode 227 Basic Calculator II
来源:互联网 发布:大赢家软件 编辑:程序博客网 时间:2024/06/13 18:56
题目描述
Implement a basic calculator to evaluate a simple expression string.
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
Note: Do not use the eval built-in library function.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析
分两次遍历,第一次遍历时,遇到乘除符号就计算;第二次遍历,计算加减符号。
参考:http://blog.csdn.net/xudli/article/details/46644317
代码
public static int calculate(String s) { if (s == null || s.length() == 0) { return 0; } Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { int val = c - '0'; // 将数字取出 while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { val = val * 10 + s.charAt(++i) - '0'; } // 栈顶是 * / 运算符,计算 if (!stack.isEmpty() && (stack.peek() == 2 || stack.peek() == 3)) { int sign = stack.pop(); int op = stack.pop(); int rt = 0; if (sign == 2) { rt = op * val; } else { rt = op / val; } stack.push(rt); } else { stack.push(val); } } else if (c == ' ') { continue; } else { switch (c) { case '+': stack.push(0); break; case '-': stack.push(1); break; case '*': stack.push(2); break; case '/': stack.push(3); break; } } } if (stack.isEmpty()) { return 0; } // 因为要从左向右计算,所以要reverse Collections.reverse(stack); // 计算+- int rt = stack.pop(); while (!stack.isEmpty()) { int sign = stack.pop(); int op = stack.pop(); if (sign == 0) { rt += op; } else { rt -= op; } } return rt; }
2 0
- leetcode 227 Basic Calculator II
- leetcode 227: Basic Calculator II
- Leetcode 227 Basic Calculator II
- Basic Calculator II - LeetCode 227
- leetcode[227]:Basic Calculator II
- LeetCode(227)Basic Calculator II
- [LeetCode 227] Basic Calculator II
- leetcode 227: Basic Calculator II
- Leetcode 227 Basic Calculator II
- leetcode 227: Basic Calculator II
- LeetCode 227 Basic Calculator II
- LeetCode[227] Basic Calculator II
- LeetCode 227 Basic Calculator II
- Leetcode 227 Basic Calculator II
- [LeetCode] Basic Calculator II
- [leetcode] Basic Calculator II
- leetcode Basic Calculator II
- 【LeetCode】Basic Calculator II
- 自动更新Android应用后, app 进入后台重进会重启
- Linux修改hostname导致无法解析主机错误
- jquery左侧导航
- Xcode真机测试could not find developer disk image解决方法
- springmvc整合shiro权限控制
- LeetCode 227 Basic Calculator II
- 高仿糯米iOS客户端应用项目源码
- get_gpio_attr()和read_gpio()
- Python 字符串操作方法大全
- BLE 包结构及传输速率
- APUE学习记录(二)
- background-position 用法详细介绍
- 基于jQuery实现复选框是否选中进行答题提示
- Java之枚举、自动装箱与注解(元数据)