当前位置:   article > 正文

【东华大学oj】基本计算器_oj基本计算器

oj基本计算器

基本计算器

时间限制: 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为一个有效表达式

输出说明

输出一行,表示结果

  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <cctype>
  5. using namespace std;
  6. int evaluate(const string &s) {
  7. stack<int> operands;
  8. stack<char> operators;
  9. int operand = 0;
  10. int result = 0;
  11. int sign = 1;
  12. for (char ch : s) {
  13. if (isdigit(ch)) {
  14. operand = 10 * operand + (ch - '0');
  15. } else if (ch == '+' || ch == '-') {
  16. result += sign * operand;
  17. operand = 0;
  18. sign = (ch == '+') ? 1 : -1;
  19. } else if (ch == '(') {
  20. operands.push(result);
  21. operators.push(sign);
  22. result = 0;
  23. sign = 1;
  24. } else if (ch == ')') {
  25. result += sign * operand;
  26. result *= operators.top();
  27. operators.pop();
  28. result += operands.top();
  29. operands.pop();
  30. operand = 0;
  31. }
  32. }
  33. return result + (sign * operand);
  34. }
  35. int main() {
  36. string s;
  37. getline(cin, s);
  38. cout << evaluate(s) << endl;
  39. return 0;
  40. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/869060
推荐阅读
相关标签
  

闽ICP备14008679号