Java elegant solution, no stack, O(n) time, beat 99%, easiest to understand


  • 0
    B

    Used two pointers:

    public class Solution {
        public int calculate(String s) {
            long v1 = 0, v2 = 0, res = 0;
            int len = s.length();
            char sign = '+';
            char[] arr = s.toCharArray();
            for (int i = 0; i <= len; i++) {
                char c = i == len ? '+' : arr[i];
                if (c == ' ') continue;
                if (c >= '0' && c <= '9') {
                    v2 = v2 * 10 + c - '0';
                    continue;
                }
                if (sign == '+') {
                    res += v1;
                    v1 = v2;
                } else if (sign == '-') {
                    res += v1;
                    v1 = -v2;
                } else if (sign == '*') {
                    v1 *= v2;
                } else if (sign == '/') {
                    v1 /= v2;
                }
                sign = c;
                v2 = 0;
            }
            res += v1;
            return (int)res;
        }
    }
    

  • 0
    R
    This post is deleted!

  • 0
    Y
    This post is deleted!

Log in to reply
 

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