[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 ...
随机推荐
- [AI] 切换cuda版本的万金油
1. 环境 ubuntu16.04 GTX1080Ti x 4 nvidia-418 cuda-10.1 pytorch1.0.0 目标:在最新的显卡驱动下,使用不同版本的cuda和深度学习框架来执行 ...
- 【原创】STM32低功耗模式及中断唤醒(基于BMI160及RTC)的研究
预研目标 六轴静止时,终端进入低功耗模式:六轴震动时,终端正常工作模式,从而极大减少非工作时的电流消耗. 解决方案 机器静止时,依据六轴算法,CPU进入休眠(停止)模式:机器工作时,触发六轴中断唤醒C ...
- 【Selenium-WebDriver实战篇】ScreenRecorder的实际输出路径设置(转)
参考:https://www.cnblogs.com/yongfeiuall/p/4134139.html 我们可以用以下方式在Selenium Webdriver中capture video. 基本 ...
- STLNormalFunc
#include <iostream> #include <vector> using namespace std; void main_1() { vector<int ...
- 关于Java的i++和++i的区别
之前对于 i++ 和 ++i 的理解就是: int i=1,a=0; 1.i++ 先运算在赋值,例如 a=i++,先运算a=i,后运算i=i+1,所以结果是a==1 2.++i 先赋值在运算,例如 a ...
- [BZOJ 5127][Lydsy1712月赛]数据校验
Description 题库链接 给你一个长度为 \(n\) 的序列.\(m\) 次询问,每次询问序列的一个区间 \([l,r]\).对于 \([l,r]\) 内的所有子区间,询问值域是否连续.若存在 ...
- EF实体类指定部分属性不映射数据库标记
命名空间 ;using System.ComponentModel.DataAnnotations.Schema; 实体部分 public partial class Student { [NotMa ...
- LeetCode 1139. Largest 1-Bordered Square
原题链接在这里:https://leetcode.com/problems/largest-1-bordered-square/ 题目: Given a 2D grid of 0s and 1s, r ...
- 创建nextcloud所需的数据库和账户
创建 nextcloud 所需的数据库和账户 打开数据库管理命令行,默认root没密码,回车进入 sudo mysql -u root -p 创建 nextcloud 数据库,命令包含后面的分号 ...
- vue+elementUI完成注册及登陆
1. vue怎么引入和配置使用element-ui框架 1.1 使用vue-cli脚手架工具创建一个vue项目 vue init webpack pro01 1.2 npm安装elementUI cd ...