28 {
29 int total_value = 0;
30
31 stringstream str_st(s);
32 bool contains_opening_bracket = false;
33 char current_sign;
34 str_st >> current_sign;
35 if (current_sign == '+' || current_sign == ')')
36 throw runtime_error(string("Invalid syntax: s string starts with ") + current_sign);
37 while (str_st >> current_sign)
38 {
39 if (current_sign == ')')
40 throw runtime_error("Invalid syntax: closing bracket appears before opening bracket");
41 if (current_sign == '(')
42 {
43 contains_opening_bracket = true;
44 break;
45 }
46 }
47
48
49 if (!contains_opening_bracket)
50 {
51 stringstream str_st(s);
52 bool is_first = true;
53 char operation = '\0';
54 int current_value = 0;
55 int current_radix_value = 1;
56
57 while (str_st >> current_sign)
58 {
59 if (isdigit(current_sign))
60 {
61 current_value *= current_radix_value;
62 current_value += atoi(string(1, current_sign).c_str());
63 current_radix_value *= 10;
64 }
65 else
66 {
67 current_radix_value = 1;
68
69 if (is_first)
70 {
71 if (operation == '-')
72 total_value -= current_value;
73 else
74 total_value += current_value;
75 current_value = 0;
76 is_first = false;
77 }
78 else
79 {
80 total_value =
evaluate(current_value, total_value, operation);
81 current_value = 0;
82 }
83
84 operation = current_sign;
85 }
86 }
87
88
89 return evaluate(current_value, total_value, operation);
90 }
91 else
92 {
93 stack<int> bracket_indices;
94 for (int i = 0; i < (int)s.size(); ++i)
95 {
96 if (s[i] == '(')
97 bracket_indices.push(i);
98 else if (s[i] == ')')
99 {
100 if (bracket_indices.empty())
101 throw runtime_error("Invalid syntax: unmatched closing bracket");
102
103 int start = bracket_indices.top();
104 bracket_indices.pop();
105
106 string inner_expression = s.substr(start + 1, i - start - 1);
107 int inner_result =
calculate(inner_expression);
108
109
110 string left_part = s.substr(0, start);
111 string right_part = s.substr(i + 1);
112 s = left_part + to_string(inner_result) + right_part;
113
114
115 i = start - 1;
116 }
117 }
118
119 if (!bracket_indices.empty())
120 throw runtime_error("Invalid syntax: unmatched opening bracket");
121
123 }
124
125 return total_value;
126 }
int evaluate(int current_value, int total_value, char operation)