Basic Calculator II(Leetcode)

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.

实现一个计算器,可以进行正数的加减乘除运算.

思路:和上一题的思路类似,遍历所有字符,得到数字,针对不同的运算符进行不同的操作。借助stack存储所有中间结果,最后依次运算。

class Solution {
public:
	int calculate(string s) {
		int res = 0, num = 0, n = s.size();
		char op = '+';//第一个数永远是整数
		stack<int> st;
		for (int i = 0; i < n; i++) {
			if (isdigit(s[i])) {
				num = num * 10 + s[i]-'0';//得到数字
			}
			if ((s[i] < '0' && s[i] != ' ') || (i==n-1)) {//最后一个数要进入运算
				if (op == '+') {
					st.push(num);
				}
				if (op == '-') {
					st.push(-num);
				}
				if (op == '*') {
					int tmp = st.top()*num;
					st.pop();//弹出第一个数
					st.push(tmp);
				}
				if (op == '/') {
					int tmp = st.top()/num;
					st.pop();
					st.push(tmp);
				}
				op = s[i];
				num = 0;
			}
		}
		while (!st.empty()) {
			res += st.top();
			st.pop();
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80870620