码迷,mamicode.com
首页 > 其他好文 > 详细

练习题 (七)

时间:2015-07-02 17:04:09      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23

解答:

class Solution {
public:
    int calculate(string s) {
        // the given expression is always valid!!!
        // only + and - !!!
        // every + and - can be flipped base on it‘s depth in ().
        stack<int> signs;
        int sign = 1;
        int num = 0;
        int ans = 0;

        // always transform s into ( s )
        signs.push(1);

        for (auto c : s) {
            if (c >= 0 && c <= 9) {
                num = 10 * num + c - 0;
            } else if (c == + || c == -) {
                ans = ans + signs.top() * sign * num;
                num = 0;
                sign = (c == + ? 1 : -1);
            } else if (c == () {
                signs.push(sign * signs.top());
                sign = 1;
            } else if (c == )) {
                ans = ans + signs.top() * sign * num;
                num = 0;
                signs.pop();
                sign = 1;
            }
        }

        if (num) {
            ans = ans + signs.top() * sign * num;
        }

        return ans;
    }
};

心得:

这个解答是我参考答案得来的。这里用sign存放“+”号或者"-"号,用signs存放sign * signs.top()括号里的累积和,用signs.push(1)做了一个栈的底。把top和pop分开写,这样使top()可以参与运算。

还有一个重要的是,栈运算能起到类似递归的作用,但是递归感觉是从最外的括号运算到最里面的括号的,但是栈运算是从最里面的右括号开始。这个栈运算值得好好体会一下。

括号加四则运算的方法,好像书本上讲的是按照什么二叉树来做的,这个感觉以前理解过,不过这次又忘记了。遇到再说吧。

练习题 (七)

标签:

原文地址:http://www.cnblogs.com/ender-cd/p/4616336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!