22. 仿LISP运算

146 阅读3分钟

题目描述

LISP 语言唯一的语法就是括号要配对。

形如 (OP P1 P2 …),括号内元素由单个空格分割。

其中第一个元素 OP 为操作符,后续元素均为其参数,参数个数取决于操作符类型。

注意:

参数 P1, P2 也有可能是另外一个嵌套的 (OP P1 P2 …) ,当前 OP 类型为 add / sub / mul / div(全小写),分别代表整数的加减乘除法,简单起见,所有 OP 参数个数均为 2 。

举例:

  • 输入:(mul 3 -7)输出:-21
  • 输入:(add 1 2) 输出:3
  • 输入:(sub (mul 2 4) (div 9 3)) 输出 :5
  • 输入:(div 1 0) 输出:error

题目涉及数字均为整数,可能为负;

不考虑 32 位溢出翻转,计算过程中也不会发生 32 位溢出翻转,

除零错误时,输出 “error”,

除法遇除不尽,向下取整,即 3/2 = 1

输入描述

输入为长度不超过512的字符串,用例保证了无语法错误

输出描述

输出计算结果或者“error”

用例

输入(div 12 (sub 45 45))
输出error
说明45减45得0,12除以0为除零错误,输出error
输入(add 1 (div -7 3))
输出-2
说明-7除以3向下取整得-3,1加-3得-2

题目解析

本题可以使用栈来解题。

首先,定义一个栈 stack。

然后,遍历输入串 s 的每一个字符 c:

  • 若 c 不是 '('、')'、' ' 这三个字符,那么 c 一定是用于组成 op 或 p1 或 p2 的字符,我们可以定义一个字符串 sb,用于收集这类字符,即 sb += c

当 c == ' ' || c == ')' 时,则此时 sb 已经完成了某个 op 或 p1 或 p2 的收集,我们将此时 sb 压入 stack 中,并且清空 sb 容器。

  • 若 c 是 ')' 则说明某个括号已经闭合,此时栈 stack 顶部三个元素,就是该闭合括号内的 op,p1,p2,我们计算出其结果后,将结果重新压入栈 stack 中

计算过程中,可能会发生除0异常,并且除法时,需要注意结果向下取整。

每遍历到 c == ')',stack就会弹栈3个元素,并计算3个元素的结果压栈。

因此,遍历完 s 串后,stack中必然只剩一个元素,该元素即为LISP表达式的整体计算结果。

#include <iostream>
#include <stack>
#include <math.h>
#include <string>
using namespace std;

string calc(string &op, int p1, int p2) {
    if (op == "add") {
        return to_string(p1 + p2);
    } else if (op == "sub") {
        return to_string(p1 - p2);
    } else if (op == "mul") {
        return to_string(p1 * p2);
    } else {
        if (p2 == 0) {
            return "error";
        }
        // 除法向下取整
        return to_string((int) floor(p1 * 1.0 / p2));
    }
}


int main()
{
    string line;
    getline(cin, line);

    stack<string> st;
    for (int i = 0; i < line.size(); i++) {
        if (line[i] == '(') {
            st.push(line.substr(i + 1, 3));
            i += 3;
        } else if (line[i] == '-' || isdigit(line[i])){
            string temp = "";
            temp.append(1, line[i]);
            i++;
            while (isdigit(line[i])) {
                temp.append(1, line[i]);
                i++;
            }
            st.push(temp);
            i--;
        } else if (line[i] == ')') {
            int b = stoi(st.top());
            st.pop();
            int a = stoi(st.top());
            st.pop();
            string op = st.top();
            st.pop();
            string res= calc(op, a, b);
            if (res == "error") {
                cout << "error";
                return 0;
            }
            st.push(res);
        }
    }

    cout << st.top();
    return 0;
}