Leetcode 227. Basic Calculator II

原題:

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.



解決方法:

用一個stack保存計算的中間結果,注意兩點:

- 減號存入的是一個相反數;

-乘號和除號需要從stack中彈出一個數,兩者相乘或相除後存入stack中。


代碼:
int calculate(string s) {
        int res = 0, num = 0;
        char sign = '+';
        stack<int> nums;
        for(int i = 0; i < s.size(); i++){
            char ch = s[i];
            if (isdigit(ch)){
                num = num * 10 + ch - '0';
            }
            
            if ( (!isdigit(ch) && !isspace(ch)) || (i == s.size() - 1) )
            {       
                if (sign == '-'){
                    nums.push(-num);
                }else if (sign == '*'){
                    int temp = num * nums.top();
                    nums.pop();
                    nums.push(temp);
                }else if (sign == '/'){
                    int temp = nums.top()/num;
                    nums.pop();
                    nums.push(temp);
                }else{
                    nums.push(num);
                }
                
                sign = ch;
                num = 0;
            }
        }
        
        while (!nums.empty()){
            res += nums.top();
            nums.pop();
        }
        return res;
    }





發佈了241 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章