solution.md 10.2 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1
# 基本计算器
F
fix bug  
feilong 已提交
2

每日一练社区's avatar
每日一练社区 已提交
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
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>

<p> </p>

<p><strong>示例 1:</strong></p>

<pre>
<strong>输入:</strong>s = "1 + 1"
<strong>输出:</strong>2
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>输入:</strong>s = " 2-1 + 2 "
<strong>输出:</strong>3
</pre>

<p><strong>示例 3:</strong></p>

<pre>
<strong>输入:</strong>s = "(1+(4+5+2)-3)+(6+8)"
<strong>输出:</strong>23
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>1 <= s.length <= * 10<sup>5</sup></code></li>
	<li><code>s</code> 由数字、<code>'+'</code><code>'-'</code><code>'('</code><code>')'</code>、和 <code>' '</code> 组成</li>
	<li><code>s</code> 表示一个有效的表达式</li>
</ul>

每日一练社区's avatar
每日一练社区 已提交
38
<p>以下<span style="color:red">错误</span>的选项是?</p>
F
fix bug  
feilong 已提交
39

每日一练社区's avatar
每日一练社区 已提交
40
## aop
F
fix bug  
feilong 已提交
41

每日一练社区's avatar
每日一练社区 已提交
42
### before
F
fix bug  
feilong 已提交
43

每日一练社区's avatar
每日一练社区 已提交
44
```cpp
每日一练社区's avatar
每日一练社区 已提交
45 46 47
#include <bits/stdc++.h>
using namespace std;
```
每日一练社区's avatar
每日一练社区 已提交
48

每日一练社区's avatar
每日一练社区 已提交
49
### after
F
fix bug  
feilong 已提交
50

每日一练社区's avatar
每日一练社区 已提交
51
```cpp
每日一练社区's avatar
每日一练社区 已提交
52 53 54 55 56 57 58 59 60 61 62 63
int main()
{
    Solution sol;
    int res;
    string s1 = "(1+(4+5+2)-3)+(6+8)";
    res = sol.calculate(s1);
    cout << res;
    return 0;
}
```

## 答案
F
fix bug  
feilong 已提交
64

每日一练社区's avatar
每日一练社区 已提交
65
```cpp
每日一练社区's avatar
每日一练社区 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
class Solution
{
public:
    int calculate(string s)
    {
        stack<string> expr, nums, ops;
        int cur = 0, len = s.size();
        string tmp = "";
        while (cur < len)
        {

            switch (s[cur])
            {
            case ' ':
                break;
            case '+':
            case '-':
            case '(':
                if (tmp != "")
                {
                    expr.push(tmp);
                    tmp = "";
                }
                expr.push(tmp + s[cur]);
                break;
            case ')':
            {
                if (tmp != "")
                {
                    expr.push(tmp);
                    tmp = "";
                }
                int caled = calculate(expr);
                expr.push(intToStr(caled));
                break;
            }
            default:
                tmp += s[cur];
                break;
            }
            ++cur;
        }
        if (tmp != "")
            expr.push(tmp);
        return calculate(expr);
    }

private:
    int calculate(stack<string> &s)
    {
        stack<int> nums;
        stack<char> ops;
        string top;

        while (!s.empty() && (top = s.top()) != "(")
        {
            if (top == "+" || top == "-")
                ops.push(top[0]);
            else
                nums.push(strToInt(top));
            s.pop();
        }
        if (!s.empty())
            s.pop();

        int ans = nums.top(), num;
        nums.pop();
        while (!ops.empty())
        {
            num = nums.top();
            nums.pop();
            if (ops.top() == '+')
                ans += num;
            else
                ans -= num;
        }
        return ans;
    }

    int strToInt(string s)
    {
        int ans = 0, len = s.size();
        if (len == 0)
            return 0;
        int symbol = s[0] == '-' ? -1 : 1;
        for (int i = s[0] == '+' || s[0] == '-' ? 1 : 0; i < len; ++i)
        {
            ans *= 10;
            ans += s[i] - '0';
        }
        return ans * symbol;
    }

    string intToStr(int num)
    {
        if (num == 0)
            return "0";
        int symbol = num >= 0 ? 1 : -1;
        string s = "";
        num *= symbol;
        while (num)
        {
            s = (char)(num % 10 + '0') + s;
            num /= 10;
        }
        if (symbol == -1)
            s = "-" + s;
        return s;
    }
};
```
## 选项

F
fix bug  
feilong 已提交
179

每日一练社区's avatar
每日一练社区 已提交
180
### A
F
fix bug  
feilong 已提交
181

每日一练社区's avatar
每日一练社区 已提交
182
```cpp
每日一练社区's avatar
每日一练社区 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class Solution
{
public:
    int calculate(string s)
    {
        stack<long> conclude;
        stack<char> fuhao;
        int i = 0, len = s.length();
        while (i < len)
        {
            if (s[i] == ' ')
                i++;
            else if (s[i] == '(')
            {
                fuhao.push('(');
                i++;
            }
            else if (s[i] == ')')
            {
                if (fuhao.top() != '(')
                {
                    long x = conclude.top();
                    conclude.pop();
                    long y = conclude.top();
                    conclude.pop();
                    if (fuhao.top() == '+')
                        conclude.push(y + x);
                    else
                        conclude.push(y - x);
                    fuhao.pop();
                }
                fuhao.pop();
                i++;
            }
            else if (s[i] == '+' || s[i] == '-')
            {
                if (!fuhao.empty() && fuhao.top() != '(')
                {
                    long x = conclude.top();
                    conclude.pop();
                    long y = conclude.top();
                    conclude.pop();
                    if (fuhao.top() == '+')
                        conclude.push(y + x);
                    else
                        conclude.push(y - x);
                    fuhao.pop();
                }
                fuhao.push(s[i]);
                i++;
            }
            else
            {
                long x = s[i] - '0';
                i++;
                while (i < len && s[i] <= '9' && s[i] >= '0')
                {
                    x = x * 10 + (s[i] - '0');
                    i++;
                }
                conclude.push(x);
            }
        }
        if (!fuhao.empty())
        {
            long x = conclude.top();
            conclude.pop();
            long y = conclude.top();
            conclude.pop();
            if (fuhao.top() == '+')
                conclude.push(y + x);
            else
                conclude.push(y - x);
            fuhao.pop();
        }
        return conclude.top();
    }
};
```

### B
F
fix bug  
feilong 已提交
264

每日一练社区's avatar
每日一练社区 已提交
265
```cpp
每日一练社区's avatar
每日一练社区 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
class Solution
{
public:
    int calculate(string s)
    {
        static const int STATE_BEGIN = 0;
        static const int NUMBER_STATE = 1;
        static const int OPERATION_STATE = 2;
        long number = 0;
        int STATE = STATE_BEGIN;
        int computer_flag = 0;
        for (int i = 0; i < s.length(); i++)
        {
            if (s[i] == ' ')
            {
                continue;
            }
            switch (STATE)
            {
            case STATE_BEGIN:
                if (s[i] >= '0' && s[i] <= '9')
                {
                    STATE = NUMBER_STATE;
                }
                else
                {
                    STATE = OPERATION_STATE;
                }
                i--;
                break;
            case NUMBER_STATE:
                if (s[i] >= '0' && s[i] <= '9')
                {
                    number = number * 10 + s[i] - '0';
                }
                else
                {
                    number_stack.push(number);
                    if (computer_flag == 1)
                    {
                        computer(number_stack, operation_stack);
                    }
                    number = 0;
                    i--;
                    STATE = OPERATION_STATE;
                }
                break;
            case OPERATION_STATE:
                if (s[i] == '+' || s[i] == '-')
                {
                    operation_stack.push(s[i]);
                    computer_flag = 1;
                }
                else if (s[i] == '(')
                {
                    computer_flag = 0;
                }
                else if (s[i] >= '0' && s[i] <= '9')
                {
                    STATE = NUMBER_STATE;
                    i--;
                }
                else if (s[i] == ')')
                {
                    computer(number_stack, operation_stack);
                }
                break;
            }
        }
        if (number != 0)
        {
            number_stack.push(number);
            computer(number_stack, operation_stack);
        }
        if (number == 0 && number_stack.empty())
        {
            return 0;
        }
        return number_stack.top();
    }
    void computer(stack<long> &number_stack, stack<char> &operation_stack)
    {
        if (number_stack.size() < 2)
        {
            return;
        }
        int num2 = number_stack.top();
        number_stack.pop();
        int num1 = number_stack.top();
        number_stack.pop();
        if (operation_stack.top() == '+')
        {
            number_stack.push(num1 + num2);
        }
        else if (operation_stack.top() == '-')
        {
            number_stack.push(num1 - num2);
        }
        operation_stack.pop();
    }

private:
    stack<long> number_stack;
    stack<char> operation_stack;
};
```

### C
F
fix bug  
feilong 已提交
374

每日一练社区's avatar
每日一练社区 已提交
375
```cpp
每日一练社区's avatar
每日一练社区 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
class Solution
{
public:
    void sum(vector<string> &stk)
    {
        vector<string> temp;
        while (!stk.empty() && stk.back() != "(")
        {
            temp.push_back(stk.back());
            stk.pop_back();
        }
        if (!stk.empty() && stk.back() == "(")
            stk.pop_back();
        if (temp.back() != "-")
            temp.emplace_back("+");
        reverse(temp.begin(), temp.end());

        int ret = 0;
        int n = temp.size();
        for (int i = 0; i < n - 1; i += 2)
        {
            int num = stoi(temp[i + 1]);
            if (temp[i] == "-")
                num *= (-1);
            ret += num;
        }

        stk.push_back(to_string(ret));
    }
    int calculate(string s)
    {
        vector<string> stk;
        int n = s.size();
        int ret = 0;

        string temp;
        for (int i = 0; i < n; ++i)
        {
            if (isdigit(s[i]))
            {
                temp += s[i];
            }
            else if (s[i] == '+' || s[i] == '-')
            {
                if (!temp.empty())
                {
                    stk.push_back(temp);
                    temp.clear();
                }
                temp += s[i];
                stk.push_back(temp);
                temp.clear();
            }
            else if (s[i] == '(')
            {
                temp += s[i];
                stk.push_back(temp);
                temp.clear();
            }
            else if (s[i] == ')')
            {
                stk.push_back(temp);
                temp.clear();
                sum(stk);
            }
        }
        if (!temp.empty())
            stk.push_back(temp);
        sum(stk);
        if (stk.size() == 1)
            ret = stoi(stk[0]);

        return ret;
    }
};
```