227. Basic Calculator II
Solution
maintain一個stack保存運算中間值
若是op為 '*' or '/',則優先計算之後再放入stack。 反之op為'+' or '-',則直接將num以更變正數或負數的方式放入。 最後再一起加總。
public int calculate(String s) {
Stack<Integer> nums = new Stack<>();
char op = '+';
int num = 0;
for(int i = 0; i < s.length(); i++){
if(Character.isDigit(s.charAt(i))){
int start = i;
while( i < s.length() && Character.isDigit(s.charAt(i))){
i++;
}
num = Integer.parseInt(s.substring(start, i));
switch(op){
case '+' :
nums.push(num);
break;
case '-' :
nums.push(0-num);
break;
case '*' :
nums.push(nums.pop()*num);
break;
case '/' :
nums.push(nums.pop()/num);
break;
}
if(i == s.length()) break;
}
if(s.charAt(i) == ' ') continue;
op = s.charAt(i);
}
//do the final calc
int ret = 0;
for(int i : nums){
ret+=i;
}
return ret;
}
Last updated
Was this helpful?