代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105
s
consists of integers and operators ('+', '-', '*', '/')
separated by some number of spaces.s
represents a valid expression.[0, 231 - 1]
.class Solution:
def calculate(self, s: str) -> int:
num, n = 0, len(s)
pre_sign = '+'
stack = []
for i in range(n):
if s[i].isdigit():
num = num * 10 + int(s[i])
if i == n - 1 or (not s[i].isdigit() and s[i] != ' '):
if pre_sign == '+':
stack.append(num)
elif pre_sign == '-':
stack.append(-num)
elif pre_sign == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num))
pre_sign = s[i]
num = 0
res = 0
while stack:
res += stack.pop()
return res
class Solution {
public int calculate(String s) {
int num = 0;
char preSign = '+';
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0, n = s.length(); i < n; ++i) {
if (Character.isDigit(s.charAt(i))) {
num = num * 10 + (s.charAt(i) - '0');
}
if (i == n - 1 || (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ')) {
switch (preSign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
preSign = s.charAt(i);
num = 0;
}
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。