Basic Calculator in C++

C++Server Side ProgrammingProgramming

Suppose we want to create one basic calculator that will find the basic expression result. The expression can hold opening and closing parentheses, plus or minus symbol and empty spaces.

So if the string is like “5 + 2 - 3”, then the result will be 7

To solve this, we will follow these steps −

  • ret := 0, sign := 1, num := 0, n := size of s

  • Define one stack st

  • for initializing i := 0, when i < n, increase i by 1 do −

    • Define an array x = s of size i

    • if x >= '0' and x <= '9', then,

      • num = num * 10

      • num = num + (x - '0')

    • Otherwise when x is same as '(', then −

      • ret = ret + (sign * num)

      • insert ret into st

      • insert sign into st

      • ret := 0, sign := 1, num := 0

    • Otherwise when x is same as ')', then −

      • ret = ret + (sign * num), sign := 1, num := 0

      • ret = ret * top element of st

      • delete item from st

      • ret = ret + top element of st

      • delete item from st

    • Otherwise when x is same as '+', then −

      • ret = ret + (sign * num), sign := 1, num := 0

    • Otherwise when x is same as '-', then −

      • ret = ret + (sign * num), sign := - 1, num := 0

  • if num is non-zero, then,

    • ret = ret + sign * num

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int calculate(string s) {
      int ret = 0;
      int sign = 1;
      int num = 0;
      int n = s.size();
      stack <int> st;
      for(int i = 0; i < n; ++i){
         char x = s[i];
         if(x >= '0' && x <= '9'){
            num *= 10;
            num += (x - '0');
         }
         else if(x == '('){
            ret += (sign * num);
            st.push(ret);
            st.push(sign);
            ret = 0;
            sign = 1;
            num = 0;
         }
         else if(x == ')'){
            ret += (sign * num);
            sign = 1;
            num = 0;
            ret *= st.top();
            st.pop();
            ret += st.top();
            st.pop();
         }
         else if(x == '+'){
            ret += (sign * num);
            sign = 1;
            num = 0;
         }
         else if(x == '-'){
            ret += (sign * num);
            sign = -1;
            num = 0;
         }
      }
      if(num){
         ret += sign * num;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.calculate("5 + 2 - 3"));
}

Input

"5 + 2 - 3"

Output

4
raja
Published on 26-May-2020 17:39:04
Advertisements