Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int calculate(string s) {
- long long int result=0;
- long long int num=0, sign=1;
- stack<long long int> nums, ops;
- for(int i=0; i<s.size(); ++i){
- char c=s[i];
- if(c>='0' && c<='9'){
- num=10*num + c-'0'; /// For case: "23"
- }else if(c=='+'){
- result += num*sign; /// everytime meets an operator, sum up previous number
- num=0;
- sign=1; /// sign is the sign of next number
- }else if(c=='-'){
- result += num*sign; /// everytime meets an operator, sum up previous number
- num=0;
- sign=-1;
- }else if(c=='('){
- nums.push(result); /// ...(1+3+(..xx..)+...)... before go into cur (..xx..), record the forefront result (in this case it is 1+3 ) into nums array
- ops.push(sign); // record cur (..xx..) sign
- result=0; // result is to record the total value in the cur (..xx..)
- sign=1;
- }else if(c==')' && ops.size()){
- result += num*sign; /// For case: 1-(5)
- num=0;
- result = result*ops.top() + nums.top(); // ...(1+3+(..xx..)+...)... sum up cur (..xx..) and the forefront result (in this case it is 1+3 )
- nums.pop();
- ops.pop();
- }
- }
- result += num*sign; /// For the last one operation. consider the case: 1+2+3
- return result;
- }
- };
- -----------------------------
- class Solution {
- public:
- int calculate(string s) {
- int n = s.size(), ret = 0, sign = 1;
- stack<int> stk;
- for (int i = 0; i < n; i++) {
- if (isdigit(s[i])) {
- int num = s[i] - '0';
- while (i + 1 < n && isdigit(s[i + 1])) {
- num = num * 10 + (s[i + 1] - '0');
- i++;
- }
- ret += sign * num;
- } else if (s[i] == '+') {
- sign = 1;
- } else if (s[i] == '-') {
- sign = -1;
- } else if (s[i] == '(') {
- stk.push(ret);
- stk.push(sign);
- ret = 0;
- sign = 1;
- } else if (s[i] == ')') {
- ret *= stk.top();
- stk.pop();
- ret += stk.top();
- stk.pop();
- }
- }
- return ret;
- }
- };
Add Comment
Please, Sign In to add comment