We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。 整数除法仅保留整数部分。 示例 1: 输入:s = "3+2*2" 输出:7 示例 2: 输入:s = " 3/2 " 输出:1 示例 3: 输入:s = " 3+5 / 2 " 输出:5 提示: 1 <= s.length <= 3 * 105 s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开 s 表示一个 有效表达式 表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内 题目数据保证答案是一个 32-bit 整数
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
示例 1:
输入:s = "3+2*2" 输出:7 示例 2:
输入:s = " 3/2 " 输出:1 示例 3:
输入:s = " 3+5 / 2 " 输出:5
提示:
1 <= s.length <= 3 * 105 s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开 s 表示一个 有效表达式 表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内 题目数据保证答案是一个 32-bit 整数
用栈来保存之前的操作符,先处理乘法和除法,再处理加法和减法
/** * @param {string} s * @return {number} */ var calculate = function (s) { s = removeSpace(s); var stack = [], len = s.length, i = 0, j = 1; for (; i < len; i++) { var current = s[i]; if (current == ' ') { continue; } else if (current == '/') { var divisor = stack.pop(); stack.push(Math.floor(Number(divisor) / Number(s[i + 1]))); i++; } else if (current == '*') { var multiplier = stack.pop(); stack.push(Number(multiplier) * Number(s[i + 1])); i++; } else { stack.push(current); } } var result = Number(stack[0]); for (; j < stack.length; j++) { if (stack[j] == '+') { result += Number(stack[j + 1]); j++; } else if (stack[j] == '-') { result -= Number(stack[j + 1]); j++; } } return result; }; var removeSpace = function (s) { var res = []; var currentNumber = ''; for (var i = 0; i < s.length; i++) { var current = s[i]; if (current != ' ') { if ( current == '+' || current == '-' || current == '*' || current == '/' ) { res.push(current); } else { if (currentNumber) { current = Number(currentNumber) * 10 + Number(current); } if ((i + 1) < s.length && !isNaN(s[i + 1]) && s[i + 1] != ' ') { currentNumber = current; } else if ((i + 1) < s.length && isNaN(s[i + 1]) && s[i + 1] != ' ') { res.push(current); currentNumber = ''; } else { res.push(current); } } } } return res; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
用栈来保存之前的操作符,先处理乘法和除法,再处理加法和减法
解答
The text was updated successfully, but these errors were encountered: