LeetCode *** 227. Basic Calculator II

来源:互联网 发布:以前网络歌手名单大全 编辑:程序博客网 时间:2024/06/05 09:31

题目:

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.


分析:

一开始走了挺多弯路,后来发现如果把减号当作负号来用那么会减少很多弯路。同时最开始设置一个Op=‘+’,那么可以很好的解决相加的问题。


代码:

class Solution {public:int calculate(string s) {stack<int> operands;int tmp = 0,length=s.length();char Op = '+';for (int i = 0; i < length; ++i) {if (s[i] >= '0'&&s[i] <= '9')tmp = tmp * 10 + s[i] - '0';if ((!(s[i] >= '0'&&s[i] <= '9') && s[i] != ' ') || i == length - 1) {if (Op == '+')operands.push(tmp);else if (Op == '-')operands.push(-tmp);else if (Op == '*') {int i = operands.top();operands.pop();operands.push(tmp*i);}else if (Op == '/') {int i = operands.top();operands.pop();operands.push(i/tmp);}tmp = 0;Op = s[i];}}int res = 0;while (!operands.empty()) {res += operands.top();operands.pop();}return res;}};

0 0
原创粉丝点击