Problem Statement:
You are given a string, that has a valid expression.
You need to implement a calculator and evaluate it.
String will consist of +’, ‘-‘, ‘*’, ‘/’.
Solution
In this question we have to prioritize the operation of “* and /”
We will use a temp variable that will calculate the intermediate result.
The intermediate result will be calculated when we encounter “+” or “-“.
So for an expression “1 +2 * 4-5/3”, there will be three intermediate results : (+)1, (+)2 * 4, (-)5/3
For example, we have a string: “1 + 2*4 – 5/3”:
First oper will be set to “+”
Then we read ‘1’, the previous oper is ‘+’, so first temp is 1 and ‘ans = 1’
Then when we read ‘+’, op is set to be ‘+’
Then we read 2, as the open before 2 is ‘+’, so the temp ans is (+) 2
Then we read *, oper is set to *
Then we read 4, temp result is (+) 2*4.
similarly we continue
Solution in C++
#include <algorithm>
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <unordered_map>
#include <list>
using namespace std;
int calculate(string s)
{
int i = 0, result = 0, num = 0;
int temp = 0;
char op = '+';
while(i < s.size())
{
if(isdigit(s[i]))
{
num = 0;
while(i < s.size() && isdigit(s[i]))
{
num = num * 10 + s[i] - '0';
i++;
}
if(op == '+' || op == '-'){
result += temp;
temp = num * (op == '-' ? -1 : 1);
}else if(op == '*'){
temp *= num;
}else if(op == '/'){
temp /= num;
}
continue;
}
else if(s[i] != ' ') op = s[i];
i++;
}
result += temp;
return result;
}
int main()
{
string s = "1+2*4-5/3";
cout<<" The result is "<<calculate(s)<<endl;
return 0;
}
Output:
The result is 8