Sunday, November 29, 2015

[leetcode]Basic Calculator II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Solution {
    public int calculate(String s) {
        s = s.replaceAll(" ", "");
        List<String> list = new LinkedList<String>();
        String prev = "";
        int i = 0;
        while(i<s.length()){
            char current = s.charAt(i);
            if (current == '*' || current == '/'){
                int numberEnd = nextNumberRange(s, i+1);
                int op2 = Integer.valueOf(s.substring(i+1, numberEnd));
                list.add(doMath(current, Integer.valueOf(list.remove(list.size()-1)), op2)+"");
                i = numberEnd;
            }else if (current == '+' || current == '-'){
                list.add(current+"");
                i++;
            }else{
                int numberEnd = nextNumberRange(s, i);
                list.add(s.substring(i, numberEnd));
                i = numberEnd;
            }
        }
        if (list.isEmpty()) return 0;
  
        while (list.size()!=1){
            int op1 = Integer.valueOf(list.remove(0));
            char op = list.remove(0).charAt(0);
            int op2 = Integer.valueOf(list.remove(0));
            list.add(0,doMath(op, op1, op2)+"");
        }
        return Integer.valueOf(list.remove(0));
    }
    
    private int doMath(char op, int op1, int op2){
        if (op == '*') return op1*op2;
        if (op == '/') return op1/op2;
        if (op == '-') return op1-op2;
        return op1+op2;
    }
    
    
    private int nextNumberRange(String s, int starting){
        while (starting < s.length()){
            char current = s.charAt(starting);
            if (current == '*' || current == '/' 
                ||current == '-' || current == '+'){
                return starting;        
            }
            starting++;
        }
        return starting;
    }
}

No comments:

Post a Comment