Guest User

Untitled

a guest
Dec 15th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstdio>
  4. #include <stack>
  5. #include <cstdlib>
  6. #include <string.h>
  7. #include <cassert>
  8. using namespace std;
  9.  
  10. // 1 2--2+
  11.  
  12. enum Operator {
  13. PLUS, MINUS, MULTIPLY, DIVIDE
  14. };
  15.  
  16. void processOperator(stack<int>& nums, Operator op) {
  17. if (nums.size() < 2) {
  18. fprintf(stderr, "Invalid RPN\n");
  19. exit(0);
  20. }
  21.  
  22. int a = nums.top();
  23. nums.pop();
  24. int b = nums.top();
  25. nums.pop();
  26. switch (op) {
  27. case PLUS:
  28. nums.push(b + a);
  29. break;
  30. case MINUS:
  31. nums.push(b - a);
  32. break;
  33. case MULTIPLY:
  34. nums.push(b * a);
  35. break;
  36. case DIVIDE:
  37. nums.push(b / a);
  38. break;
  39. }
  40. }
  41.  
  42. int main(int argc, char* argv[])
  43. {
  44. if (argc != 2) {
  45. fprintf(stderr, "Usage: ./calc <expression>");
  46. exit(0);
  47. }
  48.  
  49. char* exp = argv[1];
  50. int len = strlen(exp);
  51.  
  52. int actNum = 0;
  53. stack<int> nums;
  54. bool minus = false;
  55.  
  56. int i = 0;
  57. while (i < len) {
  58. if (exp[i] == '+') {
  59. processOperator(nums, PLUS);
  60. ++i;
  61. } else if (exp[i] == '*') {
  62. processOperator(nums, MULTIPLY);
  63. ++i;
  64. } else if (exp[i] == '/') {
  65. processOperator(nums, DIVIDE);
  66. ++i;
  67. } else if (exp[i] == '-') {
  68. if (i < len && isdigit(exp[i + 1])) {
  69. minus = true;
  70. ++i;
  71. } else {
  72. processOperator(nums, MINUS);
  73. ++i;
  74. }
  75. } else if (isdigit(exp[i])) {
  76. while (isdigit(exp[i]) && i < len) {
  77. actNum *= 10;
  78. actNum += (exp[i] - '0');
  79. ++i;
  80. }
  81.  
  82. if (minus)
  83. actNum *= -1;
  84.  
  85. nums.push(actNum);
  86.  
  87. minus = false;
  88. actNum = 0;
  89. } else
  90. ++i;
  91. }
  92.  
  93. if (nums.size() != 1) {
  94. fprintf(stderr, "Invalid RPN\n");
  95. exit(0);
  96. }
  97.  
  98. cout << nums.top() <<endl;
  99.  
  100. return 0;
  101. }
Add Comment
Please, Sign In to add comment