forked from mahendrarathore1742/leetcode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode0227-basic-calculator-ii.cpp
More file actions
41 lines (38 loc) · 1.04 KB
/
leetcode0227-basic-calculator-ii.cpp
File metadata and controls
41 lines (38 loc) · 1.04 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
/*
* Copyright (C) 2018 all rights reserved.
*
* Author: Houmin Wei <houmin.wei@pku.edu.cn>
*
* Source: https://leetcode.com/basic-calculator
*
*/
#include <string>
using namespace std;
class Solution {
public:
int calculate(string s) {
int res = 0, curRes = 0, num = 0, n = s.size();
char op = '+';
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') {
num = num * 10 + c - '0';
}
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
switch (op) {
case '+': curRes += num; break;
case '-': curRes -= num; break;
case '*': curRes *= num; break;
case '/': curRes /= num; break;
}
if (c == '+' || c == '-' || i == n - 1) {
res += curRes;
curRes = 0;
}
op = c;
num = 0;
}
}
return res;
}
};