加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

227. Basic Calculator II

发布时间:2020-12-14 21:49:24 所属栏目:大数据 来源:网络整理
导读: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. ? Example 1:

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.

?

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

?

Note:

  • You may assume that the given expression is always valid.
  • Do not?use the?eval?built-in library function.

?

Approach #1: Stack. [Java]

class Solution {
    public int calculate(String s) {
        if (s == null || s.length() == 0) return 0;
        Stack<Integer> stack = new Stack();
        s += ‘+‘;
        char op = ‘+‘;
        for (int i = 0,n = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (c >= ‘0‘ && c <= ‘9‘) { n = n * 10 + c - ‘0‘; continue; }
            if (c == ‘ ‘) continue;
            if (op == ‘+‘) stack.push(n);
            else if (op == ‘-‘) stack.push(-n);
            else if (op == ‘*‘) stack.push(stack.pop() * n);
            else if (op == ‘/‘) stack.push(stack.pop() / n);
            op = c;
            n = 0;
        }
        
        int ret = 0;
        while (!stack.empty()) 
            ret += stack.pop();
        
        return ret;
    }
} 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读