LeetCode #772 - Basic Calculator III

题目描述:

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 .

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

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

Some examples:

"1 + 1" = 2

" 6-4 / 2 " = 4

"2*(5+5*2)/3+(6/2+8)" = 21

"(2+6* 3+5- (3*14/7+2)*5)+3"=-12

class Solution {
public:
    int calculate(string s) {
        char op='+';
        int num=0;
        int result=0;
        stack<int> x;
        int i=0;
        while(i<s.size())
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                num*=10;
                num+=s[i]-'0';
            }
            else if(s[i]=='(')
            {
                int count=0;
                int j=i;
                for (;i<s.size();i++) 
                {
                    if(s[i]=='(') count++;
                    if(s[i]==')') count--;
                    if(count==0) break;
                }
                num=calculate(s.substr(j+1,i-j-1));
            }
            if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||i==s.size()-1)
            {
                if(op=='+') x.push(num);
                else if(op=='-') x.push(-num);
                else if(op=='*') 
                {
                    int temp=x.top()*num;
                    x.pop();
                    x.push(temp);
                }
                else if(op=='/') 
                {
                    int temp=x.top()/num;
                    x.pop();
                    x.push(temp);
                }
                op = s[i];
                num = 0;
            }
            i++;
        }
        
        while (!x.empty()) 
        {
            result+=x.top();
            x.pop();
        }
        return result;
    }
};

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值