[LeetCode] 227. Basic Calculator II 基本计算器 II
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的更多相关文章
- [LeetCode] 227. Basic Calculator II 基本计算器之二
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- LeetCode#227.Basic Calculator II
题目 Implement a basic calculator to evaluate a simple expression string. The expression string contai ...
- Java for LeetCode 227 Basic Calculator II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- (medium)LeetCode 227.Basic Calculator II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- [LeetCode] 772. Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] 224. Basic Calculator 基本计算器
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- 【LeetCode】227. Basic Calculator II 解题报告(Python)
[LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...
- leetcode 224. Basic Calculator 、227. Basic Calculator II
这种题都要设置一个符号位的变量 224. Basic Calculator 设置数值和符号两个变量,遇到左括号将数值和符号加进栈中 class Solution { public: int calcu ...
- 【LeetCode】227. Basic Calculator II
Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...
随机推荐
- Django的Form另类实现SelectMultiple
昨天花了一天才解决,遇到的问题如下: 在forms.py里有一个如下的字段: jira_issue = forms.CharField( required=False, label=u"Ji ...
- Kotlin中Range与异常体系剖析
好用的集合扩展方法: 下面来看一下对于集合中好用的一些扩展方法,直接上代码: 如果我们想取出集合中的第一个值和最后一个值,用Java方式是get(0)和get(size-1),但是在Kotlin中提供 ...
- python学习之多窗口切换
多窗口切换: from selenium import webdriver d = webdriver.Firefox() d.window_handles #显示所有的窗口 d.current_wi ...
- ThreadLocal(在一个线程中共享数据)
ThreadLocal 在"事务传递Connection"参数案例中,我们必须传递Connection对象,才可以完成整个事务操作.如果不传递参数,是否可以完成?在JDK中给我们提 ...
- GO语言开发之路
Go语言开发之路 介绍 为什么学习Go语言? 开发环境准备 从零开始搭建Go语言开发环境 VS Code配置Go语言开发环境 基础 Go语言基础之变量和常量 Go语言基础之基本数据类型 Go语言基础之 ...
- django-登录和退出及redis存储session信息
登录 1.视图函数views.py # 登录 from django.contrib.auth import authenticate, login # authenticate:user认证 log ...
- crc计算工具推荐
比较好的crc计算工具,32位64位系统都可以用的.crc的校验方法也很多.推荐使用 下载地址
- mssql 清理死锁
-存储过程 我们可以使用以下存储过程来检测,就可以查出引起死锁的进程和SQL语句.SQL Server自带的系统存储过程sp_who和sp_lock也可以用来查找阻塞和死锁, 但没有这里介绍的方法好用 ...
- AtCoder Beginner Contest 127 解题报告
传送门 非常遗憾.当天晚上错过这一场.不过感觉也会掉分的吧.后面两题偏结论题,打了的话应该想不出来. A - Ferris Wheel #include <bits/stdc++.h> u ...
- 树的点分治 板题 Luogu P3806
给定一棵有n个点的树 询问树上距离为k的点对是否存在. AC code: #include<bits/stdc++.h> using namespace std; const int MA ...