Skip to content

Instantly share code, notes, and snippets.

@oskimura
Created July 23, 2016 00:48
Show Gist options
  • Save oskimura/259aad2b0b7d99a645494020131e8758 to your computer and use it in GitHub Desktop.
Save oskimura/259aad2b0b7d99a645494020131e8758 to your computer and use it in GitHub Desktop.
#include<vector>
#include<iostream>
#include<string>
#include<math.h>
#include<stdlib.h>
template<typename T>
class Stack {
int cur;
std::vector<T> array;
public:
Stack() {
cur = 0;
array = std::vector<T>(256);
}
void push(T v) {
cur++;
array[cur-1] = v;
}
T pop() {
T ret = array[cur-1];
cur--;
return ret;
}
};
int eval(std::vector<std::string>& v) {
Stack<int> stack;
for (int i=0;i<v.size();i++) {
std::string c = v[i];
if(c.compare("+")==0) {
int a = stack.pop();
int b = stack.pop();
//printf("%d + %d \n",b,a);
stack.push(a + b) ;
}
else if(c.compare("-")==0) {
int a = stack.pop();
int b = stack.pop();
//printf("%d - %d \n",a,b);
stack.push(b - a) ;
}
else if(c.compare("*")==0) {
int a = stack.pop();
int b = stack.pop();
//printf("%d * %d \n",a,b);
stack.push(a * b) ;
}
else if(c.compare("/")==0) {
int a = stack.pop();
int b = stack.pop();
//printf("%d + %d \n",b,a);
stack.push(b / a) ;
}
else {
//printf("push %s\n",c.c_str());
stack.push(atoi(c.c_str()));
}
}
return stack.pop();
}
bool is_num(char c)
{
if(c=='0'||
c=='1'||
c=='2'||
c=='3'||
c=='4'||
c=='5'||
c=='6'||
c=='7'||
c=='8'||
c=='9') {
return true;
}
else {
return false;
}
}
std::vector<std::string> parse(std::string str)
{
std::vector<std::string> retval;
for (int i=0;i<str.size();i++) {
char c = str[i];
switch (c) {
case '+': {
retval.push_back("+");
break;
}
case '-': {
retval.push_back("-");
break;
}
case '*': {
retval.push_back("*");
break;
}
case '/': {
retval.push_back("/");
break;
}
default : {
if (is_num(c)) {
std::string s;
s+=c;
i++;
char c = str[i];
while(is_num(c)) {
s+=c;
i++;
c = str[i];
}
retval.push_back(s);
i--;
}
}
}
}
return retval;
}
int main()
{
Stack<std::string> stack;
std::string str;
getline(std::cin,str);
std::vector<std::string> v = parse(str);
int ret = eval(v);
std::cout << ret << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment