-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculatorII3.cpp
61 lines (47 loc) · 1.2 KB
/
BasicCalculatorII3.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
61
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
int calculate(string s) {
int result = 0;
int pre = 0;
int num = 0;
char sign = '+';
s = '+' + s + '+';
for(int i=0;i<s.length();i++){
char c = s[i];
if(c == ' ') continue;
if(c >= '0' && c <= '9'){
num = num * 10 + s[i] - '0';
}else{
if(sign == '+') {
result += pre;
pre = num;
}
if(sign == '-') {
result += pre;
pre = -num;
}
if(sign == '*'){
pre = pre * num;
}
if(sign == '/') {
pre = pre / num;
}
sign = c;
num = 0;
}
}
result += pre;
return result;
}
};
int main(){
string s;
getline(cin, s);
Solution *solution = new Solution();
cout<<solution->calculate(s);
return 0;
}