Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negativeintegers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这道题是之前那道 Basic Calculator 的拓展,不同之处在于那道题的计算符号只有加和减,而这题加上了乘除,那么就牵扯到了运算优先级的问题,好在这道题去掉了括号,还适当的降低了难度,估计再出一道的话就该加上括号了。不管那么多,这道题先按木有有括号来处理,由于存在运算优先级,我们采取的措施是使用一个栈保存数字,如果该数字之前的符号是加或减,那么把当前数字压入栈中,注意如果是减号,则加入当前数字的相反数,因为减法相当于加上一个相反数。如果之前的符号是乘或除,那么从栈顶取出一个数字和当前数字进行乘或除的运算,再把结果压入栈中,那么完成一遍遍历后,所有的乘或除都运算完了,再把栈中所有的数字都加起来就是最终结果了,参见代码如下:

解法一:

class Solution {
public:
int calculate(string s) {
long res = , num = , n = s.size();
char op = '+';
stack<int> st;
for (int i = ; i < n; ++i) {
if (s[i] >= '') {
num = num * + s[i] - '';
}
if ((s[i] < '' && s[i] != ' ') || i == n - ) {
if (op == '+') st.push(num);
if (op == '-') st.push(-num);
if (op == '*' || op == '/') {
int tmp = (op == '*') ? st.top() * num : st.top() / num;
st.pop();
st.push(tmp);
}
op = s[i];
num = ;
}
}
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};

在做了 Basic Calculator III 之后,再反过头来看这道题,发现只要将处理括号的部分去掉直接就可以在这道题上使用,参见代码如下:

解法二:

class Solution {
public:
int calculate(string s) {
long res = , curRes = , num = , n = s.size();
char op = '+';
for (int i = ; i < n; ++i) {
char c = s[i];
if (c >= '' && c <= '') {
num = num * + c - '';
}
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - ) {
switch (op) {
case '+': curRes += num; break;
case '-': curRes -= num; break;
case '*': curRes *= num; break;
case '/': curRes /= num; break;
}
if (c == '+' || c == '-' || i == n - ) {
res += curRes;
curRes = ;
}
op = c;
num = ;
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/227

类似题目:

Basic Calculator III

Basic Calculator

Expression Add Operators

参考资料:

https://leetcode.com/problems/basic-calculator-ii/

https://leetcode.com/problems/basic-calculator-ii/discuss/63003/Share-my-java-solution

https://leetcode.com/problems/basic-calculator-ii/discuss/63004/17-lines-C++-easy-20-ms

https://leetcode.com/problems/basic-calculator-ii/discuss/63031/Simple-C++-solution-beats-85-submissions-with-detailed-explanations

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 227. Basic Calculator II 基本计算器之二的更多相关文章

  1. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  2. [LeetCode] 227. Basic Calculator II 基本计算器 II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  3. LeetCode#227.Basic Calculator II

    题目 Implement a basic calculator to evaluate a simple expression string. The expression string contai ...

  4. Java for LeetCode 227 Basic Calculator II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  5. (medium)LeetCode 227.Basic Calculator II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  6. 【LeetCode】227. Basic Calculator II 解题报告(Python)

    [LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

  7. leetcode 224. Basic Calculator 、227. Basic Calculator II

    这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...

  8. 【LeetCode】227. Basic Calculator II

    Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...

  9. 224. Basic Calculator + 227. Basic Calculator II

    ▶ 两个四则表达式运算的题目,第 770 题 Basic Calculator IV 带符号计算不会做 Orz,第 772 题 Basic Calculator III 要收费 Orz. ▶ 自己的全 ...

随机推荐

  1. 转 Yolov3转化Caffe框架详解

    转自https://blog.csdn.net/watermelon1123/article/details/82083522 前些日子因工程需求,需要将yolov3从基于darknet转化为基于Ca ...

  2. kali渗透综合靶机(十五)--Breach-1.0靶机

    kali渗透综合靶机(十五)--Breach-1.0靶机 靶机下载地址:https://download.vulnhub.com/breach/Breach-1.0.zip 一.主机发现 1.netd ...

  3. datatable转layui表格v2[分页and带模板]【偏实例】

    本项目由普通mvc+webapi接口构成.按执行顺序,代码如下:主控制器:public ActionResult Index(int id=0) { ViewData["myid" ...

  4. Python - 常规操作Excel - 第二十六天

    前言 作为一名资深程序员,通过代码熟练操作Excel是必不可少的技能,本章主要讲解Python通过openpyxl第三方库(官方文件说明)对Excel进行操作,使Excel程序化操作更为简单快捷. o ...

  5. oracle创建删除视图

    --删除视图--DROP VIEW CQICC.V_APPLY_RECRUIT; --多表创建视图 CREATE OR REPLACE FORCE VIEW CQICC.V_APPLY_RECRUIT ...

  6. asp.net实现页面跳转后不可以返回

    window.history.go(0); Response.Write("<script> window.history.go(0);alert('恭喜user注册成功!!!\ ...

  7. python3之本地文件模拟登录

    本地文件模拟登录 user.txt文本文件数据格式: username:password #coding:utf-8 #读取数据 userFile = open("user.txt" ...

  8. shell脚本实现自动化安装linux版本的loadrunner agent(centos6.8)

    #!/bin/bash #Centos6下安装LoadRunner负载机 #@author Agoly #@date #@source 高级测试技术交流圈: yum -y install expect ...

  9. CTF必备技能丨Linux Pwn入门教程——环境配置

    说在前面 这是一套Linux Pwn入门教程系列,作者依据Atum师傅在i春秋上的Pwn入门课程中的技术分类,并结合近几年赛事中出现的一些题目和文章整理出一份相对完整的Linux Pwn教程. 问:为 ...

  10. cpu开多少线程合适(转)

    影响最佳线程数的主要因素: 1.IO 2.CPU 根据公式:服务器端最佳线程数量=((线程等待时间+线程cpu时间)/线程cpu时间) * cpu数量 一般来说是IO和CPU.IO开销较多的应用其CP ...