标签:
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
大意:一个不包含括号,包含空格的计算器
采用堆栈实现。从头到尾扫描字符串:
注意,使用后缀表达式,先读出两个数在读出符号,顺序应为:
这样就相当于完成了普通表达式到后缀表达式的转换。
class Solution { public: int calculate(string s) { stack<int> myStack; char sign = ‘+‘; int num = 0,res=0; for (int i = 0; i < s.size(); i++){ if (isdigit(s[i])) num = num * 10 + s[i] - ‘0‘; if (((!isdigit(s[i])) && (!isspace(s[i])))||(i==s.size()-1)){ if (sign == ‘+‘) myStack.push(num); if (sign == ‘-‘) myStack.push(num*-1); if (sign == ‘*‘){ num = myStack.top()*num; myStack.pop(); myStack.push(num); } if (sign == ‘/‘){ num = myStack.top() / num; myStack.pop(); myStack.push(num); } sign = s[i]; num = 0; } } while (!myStack.empty()){ res += myStack.top(); myStack.pop(); } return res; } };
关于”ctype.h”
图片来自维基百科<https://zh.wikipedia.org/wiki/Ctype.h>
LeetCode#227.Basic Calculator II
标签:
原文地址:http://www.cnblogs.com/yatesxu/p/5471225.html