赞
踩
时间限制: 1s
类别: DS:栈->栈的应用
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = "1 + 1"
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = "(1+(4+5+2)-3)+(6+8)"
输出:23
说明:
1 <= s.length <= 3 * 10^5
s 由数字、'+'、'-'、'('、')'、和 ' ' 组成
s 表示一个有效的表达式
'+' 不能用作一元运算(例如, "+1" 和 "+(2 + 3)" 无效)
'-' 可以用作一元运算(即 "-1" 和 "-(2 + 3)" 是有效的)
输入中不存在两个连续的操作符
每个数字和计算的结果将不超过有符号的32位整数(即int型整数)的表示范围
输入一行字符串s,s 由数字、'+'、'-'、'('、')'、和 ' ' 组成,s为一个有效表达式
输出一行,表示结果
- #include <iostream>
- #include <stack>
- #include <string>
- #include <cctype>
-
- using namespace std;
-
- int evaluate(const string &s) {
- stack<int> operands;
- stack<char> operators;
- int operand = 0;
- int result = 0;
- int sign = 1;
-
- for (char ch : s) {
- if (isdigit(ch)) {
- operand = 10 * operand + (ch - '0');
- } else if (ch == '+' || ch == '-') {
- result += sign * operand;
- operand = 0;
- sign = (ch == '+') ? 1 : -1;
- } else if (ch == '(') {
- operands.push(result);
- operators.push(sign);
- result = 0;
- sign = 1;
- } else if (ch == ')') {
- result += sign * operand;
- result *= operators.top();
- operators.pop();
- result += operands.top();
- operands.pop();
- operand = 0;
- }
- }
- return result + (sign * operand);
- }
-
- int main() {
- string s;
- getline(cin, s);
- cout << evaluate(s) << endl;
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。