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.

Java:

public int calculate(String s) {
int md=-1; // 0 is m, 1 is d
int sign=1; // 1 is +, -1 is -
int prev=0;
int result=0; for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
int num = c-'0';
while(++i<s.length() && Character.isDigit(s.charAt(i))){
num = num*10+s.charAt(i)-'0';
}
i--; // back to last digit of number if(md==0){
prev = prev * num;
md=-1;
}else if(md==1){
prev = prev / num;
md=-1;
}else{
prev = num;
}
}else if(c=='/'){
md=1;
}else if(c=='*'){
md=0;
}else if(c=='+'){
result = result + sign*prev;
sign=1;
}else if(c=='-'){
result = result + sign*prev;
sign=-1;
}
} result = result + sign*prev;
return result;
}

Python:

class Solution:
# @param {string} s
# @return {integer}
def calculate(self, s):
operands, operators = [], []
operand = ""
for i in reversed(xrange(len(s))):
if s[i].isdigit():
operand += s[i]
if i == 0 or not s[i-1].isdigit():
operands.append(int(operand[::-1]))
operand = ""
elif s[i] == ')' or s[i] == '*' or s[i] == '/':
operators.append(s[i])
elif s[i] == '+' or s[i] == '-':
while operators and \
(operators[-1] == '*' or operators[-1] == '/'):
self.compute(operands, operators)
operators.append(s[i])
elif s[i] == '(':
while operators[-1] != ')':
self.compute(operands, operators)
operators.pop() while operators:
self.compute(operands, operators) return operands[-1] def compute(self, operands, operators):
left, right = operands.pop(), operands.pop()
op = operators.pop()
if op == '+':
operands.append(left + right)
elif op == '-':
operands.append(left - right)
elif op == '*':
operands.append(left * right)
elif op == '/':
operands.append(left / right)

C++:

class Solution {
public:
int calculate(string s) {
int res = 0, d = 0;
char sign = '+';
stack<int> nums;
for (int i = 0; i < s.size(); ++i) {
if (s[i] >= '0') {
d = d * 10 + s[i] - '0';
}
if ((s[i] < '0' && s[i] != ' ') || i == s.size() - 1) {
if (sign == '+') nums.push(d);
if (sign == '-') nums.push(-d);
if (sign == '*' || sign == '/') {
int tmp = sign == '*' ? nums.top() * d : nums.top() / d;
nums.pop();
nums.push(tmp);
}
sign = s[i];
d = 0;
}
}
while (!nums.empty()) {
res += nums.top();
nums.pop();
}
return res;
}
};  

C++:  

class Solution {
public:
int calculate(string s) {
stack<int64_t> operands;
stack<char> operators;
string operand;
for (int i = s.length() - 1; i >= 0; --i) {
if (isdigit(s[i])) {
operand.push_back(s[i]);
if (i == 0 || !isdigit(s[i - 1])) {
reverse(operand.begin(), operand.end());
operands.emplace(stol(operand));
operand.clear();
}
} else if (s[i] == ')' || s[i] == '*' ||
s[i] == '/') {
operators.emplace(s[i]);
} else if (s[i] == '+' || s[i] == '-') {
while (!operators.empty() && (operators.top() == '*' ||
operators.top() == '/')) {
compute(operands, operators);
}
operators.emplace(s[i]);
} else if (s[i] == '(') {
// operators at least one element, i.e. ')'.
while (operators.top() != ')') {
compute(operands, operators);
}
operators.pop();
}
}
while (!operators.empty()) {
compute(operands, operators);
}
return operands.top();
} void compute(stack<int64_t>& operands, stack<char>& operators) {
const int64_t left = operands.top();
operands.pop();
const int64_t right = operands.top();
operands.pop();
const char op = operators.top();
operators.pop();
if (op == '+') {
operands.emplace(left + right);
} else if (op == '-') {
operands.emplace(left - right);
} else if (op == '*') {
operands.emplace(left * right);
} else if (op == '/') {
operands.emplace(left / right);
}
}
};

  

类似题目:

[LeetCode] 224. Basic Calculator 基本计算器

All LeetCode Questions List 题目汇总

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

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

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

  2. LeetCode#227.Basic Calculator II

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

  3. Java for LeetCode 227 Basic Calculator II

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

  4. (medium)LeetCode 227.Basic Calculator II

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

  5. [LeetCode] 772. Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  6. [LeetCode] 224. Basic Calculator 基本计算器

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

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

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

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

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

  9. 【LeetCode】227. Basic Calculator II

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

随机推荐

  1. NFS服务启动:rpc.nfsd: writing fd to kernel failed: errno 111 (Connection refused)

    nfs重启时提示: rpc.nfsd: writing fd to kernel failed: errno 111 (Connection refused) 解决办法: 1 #service rpc ...

  2. keepalived+nginx+lnmp 网站架构

    <网站架构演变技术研究> 项目实施手册 2019年8月2日 第一章:  实验环境确认 4 1.1-1.系统版本 4 1.1-2.内核参数 4 1.1-3.主机网络参数设置 4 1-1-4 ...

  3. 实现批量添加10个用户,用户名为user01-10,密码为user后面跟3个随机字符

    #!/bin/bash ` do user="user$i" password=$( | md5sum | ) useradd user$i echo "$user$pa ...

  4. MapReduce如何解决数据倾斜?

    数据倾斜是日常大数据查询中隐形的一个BUG,遇不到它时你觉得数据倾斜也就是书本博客上的一个无病呻吟的偶然案例,但当你遇到它是你就会懊悔当初怎么不多了解一下这个赫赫有名的事故. https://www. ...

  5. C#编写简单的聊天程序(转)

    这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考.文章大体分为四个部分:程序的分析与设计.C#网络编 ...

  6. vue中点击不同的em添加class去除兄弟级class

    vue中使用v-for循环li 怎么点击每个li中的em给添加class删除兄弟元素 <html lang="en"> <head> <meta ch ...

  7. javascript 终极循环方法for... of ..推荐

    js目前有很多的循环方法,如for, forEach,  for .. in,  for of 等等,而在ES6里面,我们又增加了一些数据结构,比如set,map,Symbol等. 那么我们该选取哪一 ...

  8. XA 事务

    4.11.3 什么是XA 事务? <数据库程序员面试笔试宝典>第4章数据库基础,本章主要介绍数据库基础部分的面试题,比较适合应届毕业生,也适合由其他岗位转数据库岗位的人员.本节为大家介绍什 ...

  9. hibernate的持久化类、主键生成策略

    一.hibernate的持久化类 1.什么是持久化类: 持久化:将数据存储到关系型数据库. 持久化类:与数据库中的数据表建立了某种关系的java类.(持久化类=javabean+映射配置文件) 2.持 ...

  10. HTML之微信全屏播放视频

    不废话,上代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...