31 stringstream str_st(s);
32 bool contains_opening_bracket =
false;
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)
39 if (current_sign ==
')')
40 throw runtime_error(
"Invalid syntax: closing bracket appears before opening bracket");
41 if (current_sign ==
'(')
43 contains_opening_bracket =
true;
49 if (!contains_opening_bracket)
51 stringstream str_st(s);
53 char operation =
'\0';
54 int current_value = 0;
55 int current_radix_value = 1;
57 while (str_st >> current_sign)
59 if (isdigit(current_sign))
61 current_value *= current_radix_value;
62 current_value += atoi(
string(1, current_sign).c_str());
63 current_radix_value *= 10;
67 current_radix_value = 1;
72 total_value -= current_value;
74 total_value += current_value;
80 total_value =
evaluate(current_value, total_value, operation);
84 operation = current_sign;
89 return evaluate(current_value, total_value, operation);
93 stack<int> bracket_indices;
94 for (
int i = 0; i < (int)s.size(); ++i)
97 bracket_indices.push(i);
100 if (bracket_indices.empty())
101 throw runtime_error(
"Invalid syntax: unmatched closing bracket");
103 int start = bracket_indices.top();
104 bracket_indices.pop();
106 string inner_expression = s.substr(start + 1, i - start - 1);
107 int inner_result =
calculate(inner_expression);
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;
119 if (!bracket_indices.empty())
120 throw runtime_error(
"Invalid syntax: unmatched opening bracket");