其他分享
首页 > 其他分享> > 仿 LISP 运算

仿 LISP 运算

作者:互联网

仿 LISP 运算

题目描述:
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”
示例 1
输入:(div 12 (sub 45 45))
输出:
error

#include<iostream>
#include<vector>
#include<string>
#include<stack>
using namespace std;

int main(){
	string str="";
	while(getline(cin,str)){
		bool flag=true;
		vector<string> st;
		stack<int> res;
		int n=str.size();
		for(int i=n-1;i>=0;){
			if(str[i]=='(' || str[i]==')' || str[i]==' '){
				--i;
			}
			else if(str[i]>='a' && str[i]<='z'){
				st.push_back(str.substr(i-2,3));
				i=i-3;
			}
			else{
				string::size_type index=str.rfind(' ',i);
				st.push_back(str.substr(index+1,i-index));
				i=index;
			}
		}
		for(size_t i=0;i<st.size();++i){
			string tmp=st[i];
			if(tmp=="add" || tmp=="sub" || tmp=="mul" || tmp=="div"){
				if(res.size()<2){
					return 0;
				}
				int num2=res.top(); res.pop();
				int num1=res.top(); res.pop();
				int result=0;
				if(tmp=="add"){
					result=num1+num2;
				}
				else if(tmp=="sub"){
					result=num2-num1;
				}
				else if(tmp=="mul"){
					result=num1*num2;
				}
				else if(tmp=="div"){
					if(num1==0){
						flag=false;
					}
					else{
						result=num2/num1;
					}
				}
				res.push(result);
			}
			else{
				res.push(atoi(tmp.c_str()));
			}
		}
		if(!flag){
			cout<<"error"<<endl;
		}
		else{
			cout<<res.top()<<endl;
		}
	}
	return 0;
}

标签:tmp,运算,LISP,res,else,result,str,div
来源: https://blog.csdn.net/Mwwwwwwww/article/details/121067956