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

227. Basic Calculator II

时间:2016-06-22 19:00:13      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

==================

基本的+,-,*,/计算,利用栈

====

思路:

申请两个栈,一个符号栈op,一个数字栈num,

代码:

class Solution {
public:
    int calculate(string s) {
        stack<char> op;
        stack<int> num;
        const int n = s.size();
        char ch;
        int tmp = 0;
        int a = 0;
        for(int i = 0;i<n;i++){
            ch = s[i];
            if(ch== ) continue;
            else if(ch==* || ch==/ || ch==+ || ch==-){
                op.push(ch);
            }else if(isdigit(ch)){
                tmp = tmp*10+ch-0;
                while(i<n && isdigit(ch=s[++i])){
                    tmp = tmp*10+ch-0;
                }
                if(!op.empty()){
                    char curr_op = op.top();
                    if(curr_op == *){
                        int a = num.top();num.pop();op.pop();
                        num.push(a*tmp);
                    }else if(curr_op == /){
                        a = num.top();num.pop();op.pop();
                        num.push(a/tmp);
                    }else{
                        if(curr_op == -) tmp *=-1;
                        num.push(tmp);
                    }
                }else{
                    num.push(tmp);
                }
                tmp = 0;
                if(i==n) break;
                i--;
            }
        }

        while(!op.empty()){
            int a = num.top();num.pop();
            int b = num.top();num.pop();
            //char ch = op.top();
            op.pop();
            num.push(a+b);
        }///while
        int re = num.top();num.pop();
        return re;
    }
};

 

227. Basic Calculator II

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5608128.html

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