Line data Source code
1 : // Copyright (c) 2024 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 :
17 : #include <gtest/gtest.h>
18 :
19 : #include <numeric>
20 : #include <string>
21 : #include <vector>
22 :
23 : namespace {
24 : class Solution {
25 : public:
26 3 : int calculate(const std::string& s) {
27 3 : int len = s.length(), num = 0;
28 3 : char sign = '+';
29 3 : std::vector<int> vec;
30 23 : for (int i = 0; i < len; ++i) {
31 20 : if (std::isdigit(s[i])) {
32 8 : num = num * 10 + (s[i] - '0');
33 : }
34 20 : if ((!std::isdigit(s[i]) && s[i] != ' ') || i == len - 1) {
35 8 : switch (sign) {
36 5 : case '+':
37 5 : vec.push_back(num);
38 5 : break;
39 0 : case '-':
40 0 : vec.push_back(-num);
41 0 : break;
42 1 : case '*':
43 1 : vec.back() *= num;
44 1 : break;
45 2 : case '/':
46 2 : vec.back() /= num;
47 2 : break;
48 : }
49 8 : num = 0;
50 8 : sign = s[i];
51 : }
52 : }
53 6 : return std::accumulate(vec.begin(), vec.end(), 0);
54 3 : }
55 : };
56 : } // namespace
57 :
58 4 : TEST(Leetcode, basic_calculator_ii) {
59 1 : Solution s;
60 1 : EXPECT_EQ(7, s.calculate("3+2*2"));
61 1 : EXPECT_EQ(1, s.calculate("3 / 2 "));
62 1 : EXPECT_EQ(5, s.calculate(" 3+5 / 2 "));
63 1 : }
|