题解 | #计算器(二)#
计算器(二)
http://www.nowcoder.com/practice/a9c170bfaf7349e3acb475d786ab1c7d
将字符串按照顺序遍历:
- 如果是数字,则将上一个数字*10加上当前数字
- 如果不是数字,则将前面的数字入栈(代码中的结束符避免最后一个数字没有入栈)。
- 如果当前操作符是+或者-或者结束符,则将当前操作符前的式子进行计算,即将数字和操作符从number1栈和operation1栈中全部出栈,然后计算得出结果,将结果压栈。
- 如果当前操作符是*或者/,则记录flag=1,用于在遇到下一个操作符时,将栈顶数字和当前操作符后的数字进行运算。(这里保证了乘除的从左往右运算)。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int calculate (String s) {
// write code here
s=s.concat("&");//结束符
Stack<Integer> number1=new Stack<>();
Stack<Character> operation1=new Stack<>();
int i=0;
int flag=0;//判断上一个操作符是否是*或者/,如果是就先运算
int tmp=0;
while(i<s.length()) {
if (s.charAt(i) <= '9' && s.charAt(i) >= '0') {
tmp *= 10;
tmp += s.charAt(i) - '0';
}
else {
number1.push(tmp);
tmp=0;
if(flag==1){
int num1 = number1.pop();
int num2 = number1.pop();
char operation = operation1.pop();
if (operation == '*') {
number1.push(num2 * num1);
} else if (operation == '/') {
number1.push(num2 / num1);
}
flag=0;
}
if(s.charAt(i)=='+'||s.charAt(i)=='-'||s.charAt(i)=='&'){
while(!operation1.empty()){
int num1=number1.pop();
int num2=number1.pop();
char operation=operation1.pop();
if(operation=='+'){
number1.push(num2+num1);
}
else if(operation=='-'){
number1.push(num2-num1);
}
else if(operation=='*'){
number1.push(num2*num1);
}
else if(operation=='/'){
number1.push(num2/num1);
}
}
}
else{
flag=1;
}
operation1.push(s.charAt(i));
}
i++;
}
return number1.pop();
}
}