Who can help me with O notation for my solution?


  • 0
    O
    
        public int calculate(String s) {
            char ch;
            //Iterators
            int i = 0, first = -1;
            //Remove all spaces from string
            StringBuilder mult = new StringBuilder(s.replaceAll(" ", ""));
            //Evaluate multiplication and division
            while(i < mult.length()) {
            	ch = mult.charAt(i);
            	if (ch-48 >= 0 && ch-48 <= 9 && first == -1) {
            		first = i;
            	} else if (ch == '*' || ch == '/') {
            		mult = makeOperation(mult, first, i, ch);
            		i = first-1;
            		first = -1;
            	} else if (ch == '+' || ch == '-') {
            		first = -1;
            	}
            	i++;
            }
            i = 0;
            first = -1;
            //Evaluate addition and subtraction
            while(i < mult.length()) {
            	ch = mult.charAt(i);
            	if (ch-48 >= 0 && ch-48 <= 9 && first == -1) {
            		first = i;
            	} else if (i == 0 && ch == '-') {
            		first = 0;
            	} else if (ch == '+' || ch == '-') {
            		mult = makeOperation(mult, first, i, ch);
            		i = first-1;
            		first = -1;
            	}
            	i++; 
            }
            return Integer.parseInt(mult.toString());
        }
        
        public StringBuilder makeOperation(StringBuilder mult, int first, int second, char operator) {
        	int j = first, sign = 1;
    		int firstNum = mult.charAt(j++)-48;
    		if (firstNum < 0) {
    			sign = -1;
    			firstNum = -1*(mult.charAt(j++)-48); 
    		}
    		char inner;
    		while(j < mult.length()) {
    			inner = mult.charAt(j++);
    			if (inner-48 < 0 || inner-48 > 9) break;
    			firstNum *= 10;
    			firstNum += sign * (inner-48);
    		}
    		second++;
    		int secondNum = mult.charAt(second++)-48;
    		while(second < mult.length()) {
    			inner = mult.charAt(second++);
    			if (inner-48 < 0 || inner-48 > 9) break;
    			secondNum *= 10;
    			secondNum += (inner-48);
    		}
    		int result = 0;
    		if (operator == '+' || operator == '-') result = operator == '+' ? firstNum+secondNum : firstNum-secondNum;
    		if (operator == '*' || operator == '/') result = operator == '*' ? firstNum*secondNum : firstNum/secondNum;
    		if (second < mult.length()) second--; 
        	return mult.replace(first, second, ""+result);
        }
    

Log in to reply
 

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