13ms JAVA code with two signs ,sign1 for +- , sign2 for */


  • 1
    B
    public class Solution {
    public int calculate(String s) {
        char[] c = (s+ "+").toCharArray();
        int sign1 = 1 ,sign2 = 1, expr = 0, num = 0, item = 1;
        for(int i = 0; i < c.length; i++){
            if(Character.isDigit(c[i])){ num = num * 10 + (c[i] - '0');}
            
            else if (c[i] == '+' || c[i] == '-') {
                expr =  expr + sign1 *( sign2 == 1? item * num: item / num);  
                item = 1;
                sign2 = 1;
                num = 0; 
                sign1 = c[i]=='+'? 1: -1;
            }
            
            else if (c[i] == '*' || c[i] =='/') {
                item = sign2 == 1? item * num: item /num; 
                num = 0; 
                sign2 = c[i] == '*'? 1 : -1;
            }
        }
        return expr;
    }
    

    }


Log in to reply
 

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