2 C# Solutions with & without stack


  • 0
    L

    Solution without stack.

    public int Calculate(string s) {
        int sum = 0, head = 0, curNum = 0;
        char op = '\0';
        for(int i = 0; i <= s.Length; i++)
            if(i < s.Length && char.IsDigit(s[i])) curNum = curNum * 10 + s[i] - '0';
            else if (i == s.Length || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
                if(op == '+' || op == '-') sum += head;
                if(op == '\0') head = curNum;
                else if(op == '+') head = curNum;
                else if(op == '-') head = -curNum;
                else if (op == '*') head *= curNum;
                else if (op == '/' && curNum != 0)head /= curNum;
                if(i < s.Length) op = s[i];
                else sum += head;
                curNum = 0;
            }
        return sum;
    }
    

    With Stack

    public int Calculate(string s) {
        int[] stack = new int[s.Length];
        int maxIndex = -1;
        for (int i = 0; i < s.Length; i++)
            if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
                stack[++maxIndex] = s[i];
            else if(s[i] >= '0' && s[i] <= '9'){
                int tmp = 0;
                for (; i < s.Length && s[i] >= '0' && s[i] <= '9'; tmp = tmp * 10 + s[i++] - '0');
                i--;
                if (maxIndex > 0){
                    char tmpCh = (char)stack[maxIndex];
                    if (tmpCh == '*' || tmpCh == '/' || tmpCh == '-'){
                        maxIndex--;
                        if (tmpCh == '*') tmp *= stack[maxIndex--];
                        else if (tmpCh == '/') tmp = stack[maxIndex--] / tmp;
                        else if (tmpCh == '-'){
                            stack[++maxIndex] = '+';
                            tmp = -tmp;
                        }
                    }
                }
                stack[++maxIndex] = tmp;
            }
        while (maxIndex > 1){
            stack[maxIndex-2] = stack[maxIndex] + stack[maxIndex-2];
            maxIndex -= 2;
        }
        return stack[maxIndex--];
    }

Log in to reply
 

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