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.


题意:

实现一个基本的计算机计算一个简单的字符串表达式的值。字符串表达式仅仅包含非负整数,+、-、*、/操作符和空白字符,整数除法应该只保留整数。可以假定给定的表达式总是有效的。

note:

不要使用内置库函数eval。


思路一:

利用堆栈实现基本运算,对给定的字符串进行轮训,如果是数字且操作符是+或者-号,则将该数字压入到堆栈中,如果是操作符是*或者/号,则将栈顶元素取出之后与当前数字进行运算,将运算结果保存到堆栈中。最后堆栈中所保存的数字之间均为+运算关系,则只需要将堆栈中的数字进行累加即可获得运算结果值。

代码:Java版:42ms

public class Solution {
    public int calculate(String s) {
        int len;
        if (s == null || (len = s.length()) == 0) return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int num = 0;
        char sign = '+';
        for (int i=0; i<len; i++) {
            if (Character.isDigit(s.charAt(i))) {  //处理表达式中的数字
                num = num*10 + s.charAt(i) - '0';
            }
            if ((!Character.isDigit(s.charAt(i)) && ' '!=s.charAt(i)) || i == len-1) { //处理操作符
                if (sign == '-') {
                    stack.push(-num);
                }
                if (sign == '+') {
                    stack.push(num);
                }
                if (sign == '*') {
                    stack.push(stack.pop()*num);
                }
                if (sign == '/') {
                    stack.push(stack.pop()/num);
                }
                sign = s.charAt(i);  //保存当前运算符
                num = 0;
            }
        }
        
        int res = 0;
        for (int i : stack) { //将堆栈中的所有数累加
            res += i;
        }
        return res;
    }
}


思路二:

利用一个中间变量来保存运算过程中做乘除运算所产生的中间值,之后将结果累加到总返回结果中。主要分开加减运算与乘除运算之间的优先级运算关系。

代码:16ms

class Solution {
public:
    int calculate(string s) {
        int result = 0, cur_res = 0;
        char op = '+';
        for (int pos=s.find_first_not_of(' '); pos<s.size(); pos=s.find_first_not_of(' ', pos)) {
            if (isdigit(s[pos])) { 
                int tmp = s[pos] - '0';
                while (++pos < s.size() && isdigit(s[pos]))  //得到表达式中的一个完整操作数
                    tmp = tmp*10 + (s[pos] - '0');
                switch(op) { //根据操作符做相应的运算
                    case '+': 
                        cur_res += tmp;
                        break;
                    case '-':
                        cur_res -= tmp;
                        break;
                    case '*':
                        cur_res *= tmp;
                        break;
                    case '/':
                        cur_res /= tmp;
                        break;
                        
                }
            } else {
                if (s[pos] == '+' || s[pos] == '-') {
                    result += cur_res;
                    cur_res = 0;
                }
                op = s[pos++];
            }
        }
        return result + cur_res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值