-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathBasic Calculator.cpp
More file actions
45 lines (43 loc) · 1.35 KB
/
Basic Calculator.cpp
File metadata and controls
45 lines (43 loc) · 1.35 KB
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
/*
MY YOUTUBE VIDEO IN THIS Qn : https://www.youtube.com/watch?v=3AEKyHx3tzU
Company Tags : Google, Facebook, Airbnb
Frequency : 66% (As per 2021)
Leetcode Link : https://leetcode.com/problems/basic-calculator/
*/
class Solution {
public:
int calculate(string s) {
stack<int> st;
int number = 0;
int result = 0;
int sign = 1;
for(int i = 0; i<s.length(); i++) {
if(isdigit(s[i])) {
number = 10*number + (s[i] - '0');
} else if(s[i] == '+') {
result += sign*number;
number = 0;
sign = 1; //For further
} else if(s[i] == '-') {
result += sign*number;
number = 0;
sign = -1; //For further
} else if(s[i] == '(') {
st.push(result);
st.push(sign);
result = 0;
number = 0;
sign = 1;
} else if(s[i] == ')') {
result += sign*number;
number = 0;
int top = st.top(); st.pop();
result *= top;
top = st.top(); st.pop();
result += top;
}
}
result += (sign*number);
return result;
}
};