227. Basic Calculator II
給定一個表示算式的字串 s
,計算該算式的結果並返回其值。
整數除法應該向零截斷。
你可以假設給定的算式總是有效的。所有中間結果都會在 [-2³¹, 2³¹ - 1] 的範圍內。
注意:你不允許使用任何內建函數來直接計算字符串中的數學表達式,例如 eval()
。
範例:
輸入: s = "3+2*2"
輸出: 7
Python
class Solution:
def calculate(self, s: str) -> int:
def update(op, v):
if op == "+": stack.append(v)
if op == "-": stack.append(-v)
if op == "*": stack.append(stack.pop() * v)
if op == "/": stack.append(int(stack.pop() / v))
it, num, stack, sign = 0, 0, [], "+"
while it < len(s):
if s[it].isdigit():
num = num * 10 + int(s[it])
elif s[it] in "+-*/":
update(sign, num)
num, sign = 0, s[it]
elif s[it] == "(":
num, j = self.calculate(s[it + 1:])
it = it + j
elif s[it] == ")":
update(sign, num)
return sum(stack), it + 1
it += 1
update(sign, num)
return sum(stack)
19.89MB, 125ms
C++
class Solution {
public:
int calculate(string s) {
int length = s.length();
if (length == 0) return 0;
int currentNumber = 0, lastNumber = 0, result = 0;
char sign = '+';
for (int i = 0; i < length; i++) {
char currentChar = s[i];
if (isdigit(currentChar)) {
currentNumber = (currentNumber * 10) + (currentChar - '0');
}
if (!isdigit(currentChar) && !iswspace(currentChar) || i == length - 1) {
if (sign == '+' || sign == '-') {
result += lastNumber;
lastNumber = (sign == '+') ? currentNumber : -currentNumber;
} else if (sign == '*') {
lastNumber = lastNumber * currentNumber;
} else if (sign == '/') {
lastNumber = lastNumber / currentNumber;
}
sign = currentChar;
currentNumber = 0;
}
}
result += lastNumber;
return result;
}
};
11.04MB, 18ms
Javascript
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
// Remove all white spaces from the string
s = s.replace(/\s+/g, '');
// Initialize a stack to keep track of numbers and operations
let stack = [];
let currentNumber = 0;
let operation = '+'; // Start with an addition operation by default
for (let i = 0; i < s.length; i++) {
let currentChar = s[i];
if (!isNaN(currentChar)) {
// Build the current number
currentNumber = currentNumber * 10 + parseInt(currentChar);
}
// If the current character is an operator or we're at the end of the string
if (isNaN(currentChar) || i === s.length - 1) {
if (operation === '+') {
stack.push(currentNumber);
} else if (operation === '-') {
stack.push(-currentNumber);
} else if (operation === '*') {
stack.push(stack.pop() * currentNumber);
} else if (operation === '/') {
stack.push(Math.trunc(stack.pop() / currentNumber));
}
// Update the operation and reset currentNumber
operation = currentChar;
currentNumber = 0;
}
}
// Sum up all the numbers in the stack to get the final result
return stack.reduce((a, b) => a + b, 0);
};
58.36MB, 92ms