-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
227.cpp
112 lines (97 loc) · 3.19 KB
/
227.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
__________________________________________________________________________________________________
sample 4 ms submission
static int fastio = []() {
#define endl '\n'
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(0);
return 0;
}();
class Solution {
public:
int calculate(string s)
{
if (s.empty())
return 0;
int currentValue = 0;
int currentNumber = 0;
int lastNumber = 0;
char operation = '+';
int index = 0;
int n = s.length();
while (index < n)
{
while (index < n && s[index] == ' ') ++index;
currentNumber = 0;
while (index < n && std::isdigit(s[index]))
{
currentNumber = currentNumber * 10 + (s[index] - '0');
++index;
}
if (operation == '+')
{
currentValue += currentNumber;
lastNumber = currentNumber;
}
else if (operation == '-')
{
currentValue -= currentNumber;
lastNumber = -currentNumber;
}
else if (operation == '*')
{
currentValue = currentValue - lastNumber + lastNumber * currentNumber;
lastNumber = lastNumber * currentNumber;
}
else if (operation == '/')
{
currentValue = currentValue - lastNumber + lastNumber / currentNumber;
lastNumber = lastNumber / currentNumber;
}
while (index < n && s[index] == ' ') ++index;
if (index < n)
operation = s[index];
++index;
}
return currentValue;
}
};
__________________________________________________________________________________________________
sample 9464 kb submission
class Solution {
public:
int calculate(string s) {
if (s.empty()) return 0;
int res = 0, tmp = 0, num = 0;
char op = '+';
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
while (i < s.size() && isdigit(s[i])) {
num = 10 * num + (s[i] - '0');
i++;
}
i--; //NOTE: the i already points to the next chars in above while-loop
if (op == '+') {
res += tmp;
tmp = num;
num = 0; //reset num as it is already used
} else if (op == '-') {
res += tmp;
tmp = -1 * num;
num = 0;
} else if (op == '*') {
tmp *= num;
num = 0;
} else if (op == '/') {
tmp /= num;
num = 0;
}
} else if (s[i] != ' ') {
op = s[i];
}
}
res += tmp;
return res;
}
};
__________________________________________________________________________________________________