Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cstdio>
- #include <stack>
- #include <cstdlib>
- #include <string.h>
- #include <cassert>
- using namespace std;
- // 1 2--2+
- enum Operator {
- PLUS, MINUS, MULTIPLY, DIVIDE
- };
- void processOperator(stack<int>& nums, Operator op) {
- if (nums.size() < 2) {
- fprintf(stderr, "Invalid RPN\n");
- exit(0);
- }
- int a = nums.top();
- nums.pop();
- int b = nums.top();
- nums.pop();
- switch (op) {
- case PLUS:
- nums.push(b + a);
- break;
- case MINUS:
- nums.push(b - a);
- break;
- case MULTIPLY:
- nums.push(b * a);
- break;
- case DIVIDE:
- nums.push(b / a);
- break;
- }
- }
- int main(int argc, char* argv[])
- {
- if (argc != 2) {
- fprintf(stderr, "Usage: ./calc <expression>");
- exit(0);
- }
- char* exp = argv[1];
- int len = strlen(exp);
- int actNum = 0;
- stack<int> nums;
- bool minus = false;
- int i = 0;
- while (i < len) {
- if (exp[i] == '+') {
- processOperator(nums, PLUS);
- ++i;
- } else if (exp[i] == '*') {
- processOperator(nums, MULTIPLY);
- ++i;
- } else if (exp[i] == '/') {
- processOperator(nums, DIVIDE);
- ++i;
- } else if (exp[i] == '-') {
- if (i < len && isdigit(exp[i + 1])) {
- minus = true;
- ++i;
- } else {
- processOperator(nums, MINUS);
- ++i;
- }
- } else if (isdigit(exp[i])) {
- while (isdigit(exp[i]) && i < len) {
- actNum *= 10;
- actNum += (exp[i] - '0');
- ++i;
- }
- if (minus)
- actNum *= -1;
- nums.push(actNum);
- minus = false;
- actNum = 0;
- } else
- ++i;
- }
- if (nums.size() != 1) {
- fprintf(stderr, "Invalid RPN\n");
- exit(0);
- }
- cout << nums.top() <<endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment