Line data Source code
1 : // Copyright (c) 2022 The Authors. All rights reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : // Authors: liubang (it.liubang@gmail.com)
16 : // Created: 2022/01/17 14:50
17 :
18 : #include <gtest/gtest.h>
19 :
20 : #include <numeric>
21 : #include <string>
22 : #include <vector>
23 :
24 : namespace {
25 : class Solution {
26 : public:
27 3 : int calculate(const std::string& s) {
28 3 : int len = s.length(), num = 0;
29 3 : char sign = '+';
30 3 : std::vector<int> vec;
31 23 : for (int i = 0; i < len; ++i) {
32 20 : if (std::isdigit(s[i])) {
33 8 : num = num * 10 + (s[i] - '0');
34 : }
35 20 : if ((!std::isdigit(s[i]) && s[i] != ' ') || i == len - 1) {
36 8 : switch (sign) {
37 5 : case '+':
38 5 : vec.push_back(num);
39 5 : break;
40 0 : case '-':
41 0 : vec.push_back(-num);
42 0 : break;
43 1 : case '*':
44 1 : vec.back() *= num;
45 1 : break;
46 2 : case '/':
47 2 : vec.back() /= num;
48 2 : break;
49 : }
50 8 : num = 0;
51 8 : sign = s[i];
52 : }
53 : }
54 6 : return std::accumulate(vec.begin(), vec.end(), 0);
55 3 : }
56 : };
57 : } // namespace
58 :
59 4 : TEST(Leetcode, basic_calculator_ii) {
60 1 : Solution s;
61 1 : EXPECT_EQ(7, s.calculate("3+2*2"));
62 1 : EXPECT_EQ(1, s.calculate("3 / 2 "));
63 1 : EXPECT_EQ(5, s.calculate(" 3+5 / 2 "));
64 1 : }
|