/
calculatorI.cpp
60 lines (57 loc) · 1.87 KB
/
calculatorI.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stack>
#include <string>
#include <iostream>
using namespace std;
double solution(string input){
//intialise stack
stack<double> calcStack;
//keep track of result and current value to process
double result = 0, currNumber = 0;
//keep track of previous sin for precedence assessment
char prevSign = '+';
//iterate through entire string
for(int i = 0;i<input.size();i++){
//if current char is a digit, append to current number
if(isdigit(input[i])) currNumber = currNumber*10 + ((int)input[i]-48);
//if not a digit OR we have reached the end of the string,
//Process currentNumber
if(!isdigit(input[i]) || i ==input.size()-1){
double multValue;
switch (prevSign)
{
case '-':
calcStack.push(-currNumber);
prevSign = '-';
break;
case '+':
calcStack.push(currNumber);
prevSign= '+';
break;
//Operators below take precedence and so top of stack has operation performed on it (i.e. before summation)
//Divide and multiply are commutative, therefore can be applied one after the other
case '*':
multValue = calcStack.top() * currNumber;
calcStack.pop();
calcStack.push(multValue);
break;
case '/':
multValue = calcStack.top() * (1 / currNumber);
calcStack.pop();
calcStack.push(multValue);
break;
}
currNumber = 0;
prevSign = input[i];
}
}
//Sum over stack
while(!calcStack.empty()){
result+=calcStack.top();
calcStack.pop();
}
return result;
}
int main(){
string test{"3*3/3/3*4/3*2"};
cout<<solution(test);
}