C++ 30 lines no stack recursive solution with istringstream (28ms)


  • 1
    S

    Inspired by Stefan's solution for calculator II at https://leetcode.com/discuss/41641/17-lines-c-easy-20-ms using istringstream, my code runs in 28ms. I learned about istringstream and the nice thing about it is that we don't have to iterate through long digits and write lengthy code to keep multiplying base 10. Even though the code is fast, I still think there exists some redundancy in the code. Any improvement to make the code cleaner would be appreciated. Thanks.

    class Solution {
        public:
            int calculate(string s) {
                istringstream ss('+' + s + '+');
                return helper(ss);
            }
            
            int helper(istringstream& ss){
                int sum = 0, num; char op;
                while (ss >> op){
                    while (ss.peek() == ' ') ss.get();
        
                    if (op == '+' || op == '-'){
                        if (isdigit(ss.peek())){
                            ss >> num;
                            sum += (op=='+'? 1 : -1)*num;
                        } else {  // open paren after +
                            sum += (op=='+'? 1 : -1)*helper(ss);
                        }
                    } else if (op == '('){
                        if (isdigit(ss.peek())){
                            ss >> num;
                            sum += num;
                        } else {   // open paren nested
                            sum += helper(ss);
                        }
                    } else {  // close paren
                        return sum;
                    }
                }
                return sum;
            }
        };
    

  • 0
    Z

    I like this solution. It could be further extended to work with '*' and '/' easily.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.