赞
踩
一个栈存符号
class Solution { public: int calculate(string s) { stack<int> st({1}); int sign = 1; int res=0; int number; int n = s.size(); int i=0; while(i<n) { if(isdigit(s[i])) { number = 0; while(i < n && isdigit(s[i])){ number = number * 10 + (s[i] - '0'); i++; } res += sign * number; } else { if(s[i] == '+') sign = st.top(); else if(s[i] == '-') sign = -st.top(); else if(s[i] == '(') st.push(sign); else if(s[i] == ')') st.pop(); i ++; } } return res; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。