华为机试: 仿 LISP 运算

题目来源

题目描述

在这里插入图片描述
在这里插入图片描述

题目解析

这道题和leetcode:150. 后缀表达式求和几乎是一模一样的。考察的是字符串切割以及逆波兰表达式

#include <utility>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

class Solution{
    std::string calOne(std::stack<std::string> &stack){
        if(stack.size() < 3){
            return "error";
        }
        auto second = stoi(stack.top()); stack.pop();
        auto first = stoi(stack.top()); stack.pop();
        auto sign = stack.top(); stack.pop();
        int res = 0;
        if(sign == "add"){
            res = first + second;
        }else if(sign == "sub"){
            res = first - second;
        }else if(sign == "mul"){
            res = first * second;
        }else{
            if(second == 0){
                return "error";
            }
            res = first / second;
        }
        return to_string(res);
    }
public:
    std::string solve(std::string str){
        // 题目涉及数字均为整数,可能为负;
        std::stack<std::string> stack;
        int i = 0;
        while (i < str.size()){
            if(str[i] == '('){ // 遇见了起始
                stack.push( str.substr(i + 1, 3));
                i += 4;
            }else if((str[i] >= '0' && str[i] <= '9') || str[i] == '-'){
                int j = i;   // 找下一个' '或者')'
                while (j < str.size() && str[j] != ' ' && str[j] != ')'){
                    j++;
                }
                stack.push(str.substr(i, j - i));
                i = j;
            }else if(str[i] == ' '){
                i++;
            }else{
                auto ans = calOne(stack);
                if(ans == "error"){
                    return "error";
                }
                stack.push(ans);
                i++;
            }
        }

        return stack.empty() ? "0" : stack.top();
    }
};



int main(){
    Solution a;
    std::cout << a.solve("(mul 3 -7)") << "\n";
    std::cout << a.solve("(add 1 2)") << "\n";
    std::cout << a.solve("(sub (mul 2 4) (div 9 3))") << "\n";
    std::cout << a.solve("(div 1 0)") << "\n";
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值