[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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架