Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Last active August 10, 2019 05:24
Show Gist options
  • Save shixiaoyu/27a4b2c36eeb0054183e3725b3e10cff to your computer and use it in GitHub Desktop.
Save shixiaoyu/27a4b2c36eeb0054183e3725b3e10cff to your computer and use it in GitHub Desktop.
// Another thought is having 2 pass, first pass */, second pass +-
// "1 + 2 * 3 / 2" = 4, pretty clean
// "1 - 2 * 3 / 2" = -2
public int calculateTwoPass(String s) {
int len;
if (s == null || (len = s.length()) == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
// This is more like the previous sign
char sign = '+';
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
}
if ((!Character.isDigit(s.charAt(i)) && ' ' != s.charAt(i)) || i == len - 1) {
if (sign == '-') {
stack.push(-num);
}
if (sign == '+') {
stack.push(num);
}
if (sign == '*') {
stack.push(stack.pop()*num);
}
if (sign == '/') {
stack.push(stack.pop()/num);
}
// reassign the current sign
sign = s.charAt(i);
num = 0;
}
}
int re = 0;
for (int i : stack){
re += i;
}
return re;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment