刷题-力扣-面试题16.26. 计算器

面试题 16.26. 计算器

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/calculator-lcci/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

给定一个包含正整数、加(+)、减(-)、乘()、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,
,/ 四种运算符和空格 。 整数除法仅保留整数部分。

示例 1:

输入: "3+2*2"
输出: 7

示例 2:

输入: " 3/2 "
输出: 1

示例 3:

输入: " 3+5 / 2 "
输出: 5

说明:

  • 你可以假设所给定的表达式都是有效的。
  • 请不要使用内置的库函数 eval。

题目分析

  1. 根据题目描述计算表达式的结果
  2. 使用后进先出的原理,再根据计算符的优先级计算。类似逆波兰,建议使用逆波兰

代码

class Solution {
public:
    int calculate(string s) {
        stack<char> op;
        stack<int> num;
        int index = 0;
        while (index < s.length()) {
            if (s[index] == ' ') {
                ++index;
                continue;
            }
            if (s[index] == '+' || s[index] == '-') {
                if (op.empty()) {
                    op.push(s[index]);
                    ++index;
                } else {
                    int r = num.top();
                    num.pop();
                    int f = num.top();
                    num.pop();
                    if (op.top() == '+') num.push(f + r);
                    else if (op.top() == '-') num.push(f - r);
                    else if (op.top() == '*') num.push(f * r);
                    else if (op.top() == '/') num.push(f / r);
                    op.pop();
                }
            } else if (s[index] == '*' || s[index] == '/') {
                if (op.empty() == false && (op.top() == '*' || op.top() == '/')) {
                    int r = num.top();
                    num.pop();
                    int f = num.top();
                    num.pop();
                    if (op.top() == '*') num.push(f * r);
                    else num.push(f / r);
                    op.pop();
                }
                op.push(s[index]);
                ++index;
            } else {
                int n = s[index] - '0';
                ++index;
                while (s[index] - '0' >= 0 && s[index] - '0' <= 9) {
                    n = n * 10 + (s[index] - '0');
                    ++index;
                }
                num.push(n);
            }
        }
        while (!op.empty()) {
            int r = num.top();
            num.pop();
            int f = num.top();
            num.pop();
            if (op.top() == '+') num.push(f + r);
            else if (op.top() == '-') num.push(f - r);
            else if (op.top() == '*') num.push(f * r);
            else if (op.top() == '/') num.push(f / r);
            op.pop();
        }
        return num.top();
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/14601541.html