-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_calculator.cpp
78 lines (74 loc) · 1.85 KB
/
basic_calculator.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
/*
* =====================================================================================
*
* Filename: basic_calculator.cpp
*
* Description: 224. Basic Calculator.
* https://leetcode.com/problems/basic-calculator/
*
* Version: 1.0
* Created: 03/23/23 11:52:33
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cctype>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::stack;
using std::string;
using std::vector;
class Solution {
public:
int calculate(string s) {
stack<int> prevs;
int result = 0;
int sign = 1;
for (int i = 0; i < s.size(); i++) {
const char c = s[i];
if (std::isdigit(c)) {
int num = c - '0';
while (i + 1 < s.size() && std::isdigit(s[i + 1])) {
num = num * 10 + (s[i + 1] - '0');
i++;
}
result += sign * num;
} else if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else if (c == '(') {
prevs.push(result);
prevs.push(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result *= prevs.top();
prevs.pop();
result += prevs.top();
prevs.pop();
} else {
; // Ignore space and invalid expression
}
}
return result;
}
};
TEST(Solution, calculate) {
vector<std::pair<string, int>> cases = {
std::make_pair(string("1 + 1"), 2),
std::make_pair(string(" 2-1 + 2 "), 3),
std::make_pair(string("(1+(4+5+2)-3)+(6+8)"), 23),
};
for (const auto& c : cases) {
EXPECT_EQ(Solution().calculate(c.first), c.second);
}
}