-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculatorII4.cpp
More file actions
52 lines (42 loc) · 1.13 KB
/
BasicCalculatorII4.cpp
File metadata and controls
52 lines (42 loc) · 1.13 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
46
47
48
49
50
51
52
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
int calculate(string s) {
int result = 0;
int cur = 0;
char sign = '+';
for(int i=0;i<s.length();i++){
char c = s[i];
if(c == ' ') continue;
if(c >= '0' && c <= '9'){
int num = 0;
while(i < s.length() && s[i] >= '0' && s[i] <= '9'){
num = num * 10 + s[i] - '0';
i ++;
}
i --;
if(sign == '+') cur += num;
else if(sign == '-') cur -= num;
else if(sign == '*') cur *= num;
else if(sign == '/') cur /= num;
}else{
if(c == '+' || c == '-') {
result += cur;
cur = 0;
}
sign = c;
}
}
return result + cur;
}
};
int main(){
string s;
getline(cin, s);
Solution *solution = new Solution();
cout<<solution->calculate(s);
return 0;
}