publicclassBasicCalculatorII{ publicintcalculate(String s){ if (s == null || s.trim().length() == 0) { return0; }
s = s.replaceAll(" ", "");
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < s.length(); ) { char c = s.charAt(i); int op = isOperator(c); int end = i + 1; if (op == 2) { // for * and /, just calculate the result and store it in the list int a = list.get(list.size() - 1); list.remove(list.size() - 1); end = readNumber(s, i + 1); list.add(getResult(a, Integer.valueOf(s.substring(i + 1, end)), c)); } elseif (op == 1 && c == '-') { // if minus a number, just store thr negative format number in the list end = readNumber(s, i + 1); list.add(Integer.valueOf(s.substring(i, end))); }
if (isNumber(c)) { end = readNumber(s, i); list.add(Integer.valueOf(s.substring(i, end))); }
i = end; }
// sum up all integers int result = 0; for (int a : list) { result += a; }
return result; }
/** * Read number, and find the last index for current number * * @param s given string * @param start start index to search number * @return last index of current number */ privateintreadNumber(String s, int start){ while (start < s.length()) { if (!isNumber(s.charAt(start))) { break; } start++; } return start; }
/** * check a char is number or not * * @param c char to check * @return true for number otherwise false */ privatebooleanisNumber(char c){ return c >= '0' && c <= '9'; }
/** * Check whether it is a operator * * @param c char * @return 2 for (*, /), 1 for (+,-), otherwise 0 */ privateintisOperator(char c){ if (c == '*' || c == '/') { return2; } elseif (c == '+' || c == '-') { return1; } else { return0; } }
/** * Calculate the result * * @param x first parameter * @param y second parameter * @param c operator * @return result */ privateintgetResult(int x, int y, char c){ switch (c) { case'+': return x + y; case'-': return x - y; case'*': return x * y; case'/': return x / y; default: return0; } } }