Share my 5 variables java solution


  • 0
    D

    char save is to save the last mark

    public class Solution {
        public int calculate(String s) {
            int sum=0, tmp=0, tmpSum=0;
            char save = '0';
            for(int i=0; i<s.length(); i++) {
                char temp = s.charAt(i);
                if(Character.isDigit(temp)) {
                    tmp = tmp*10+(int)(s.charAt(i)-'0');
                }
                if(temp==' ') continue;
                if(temp=='+'||temp=='-') {
                    if(save=='*') sum +=tmp*tmpSum;
                    else if(save=='-') sum -=tmp;
                    else if(save=='/') sum +=tmpSum/tmp;
                    else sum +=tmp;
                    tmp=0;
                    tmpSum=0;
                    save = temp=='+'?'+':'-';
                }
                if(temp=='*'||temp=='/') {
                    if(save=='-') tmpSum = -tmp;
                    else if(save=='*') tmpSum = tmp*tmpSum;
                    else if(save=='/') tmpSum = tmpSum/tmp;
                    else tmpSum = tmp;
                    tmp = 0;
                    save = temp=='*'?'*':'/';
                }
            }
            int last=0;
            if(tmp!=0||tmpSum!=0) {
                if(save=='*') last = tmpSum*tmp;
                else if(save=='-') last = -tmp;
                else if(save=='/') last = tmpSum/tmp;
                else last = tmp;
            }
            return sum+last;
        }
    }

Log in to reply
 

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