几种计算器的写法
作者bibo
class Solution {
public int calculate(String s) {
Queue<Character> q = new ArrayDeque<>();
for(char c:s.toCharArray()){
if(c!=‘ ‘){
q.offer(c);
}
}
q.offer(‘ ‘);
return helper(q);
}
public int helper(Queue<Character> q){
int sum=0,prev=0,num=0;
char prevOp = ‘+’;
while(!q.isEmpty()){
char ch = q.poll();
if(Character.isDigit(ch)){
num = num*10+ch-‘0’;
}else if(ch == ‘(‘){
num = helper(q);
}else{
switch(prevOp){
case ‘+’:
sum+=prev;
prev=num;
break;
case ‘-‘:
sum+=prev;
prev=-num;
break;
}
if(ch ==‘)’){
break;
}
prevOp = ch;
num = 0;
}
}
return sum + prev;
}
}
class Solution {
public int calculate(String s) {
int sum =0,prev=0,num=0;
char prevOp=‘+’;
s=s.trim();
s = s+” “;
int n = s.length();
for(int i=0;i<n;i++){
char ch = s.charAt(i);
if(ch == ‘ ‘&&i!=n-1){
continue;
}
if(Character.isDigit(ch)){
num = num*10+ch-‘0’;
}else{
switch(prevOp){
case ‘+’:
sum+=prev;
prev=num;
break;
case ‘-‘:
sum+=prev;
prev=-num;
break;
case ‘*’:
prev*=num;
break;
case ‘/’:
if(num!=0)
prev/=num;
break;
}
num = 0;
prevOp = ch;
}
}
return sum+prev;
}
}
class Solution {
public int calculate(String s) {
Queue<Character> queue = new ArrayDeque<>();
for(char ch:s.toCharArray()){
queue.offer(ch);
}
queue.offer(‘ ‘);
return helper(queue);
}
public int helper(Queue<Character> queue){
int num =0,prev =0,sum=0;
char preOp =‘+’;
while(!queue.isEmpty()){
char c = queue.poll();
if(Character.isDigit(c)){
num = num*10+c-‘0’;
}else if(c == ‘(‘){
num = helper(queue);
}else{
switch(preOp){
case ‘+’:
sum+=prev;
prev = num;
break;
case ‘-‘:
sum+=prev;
prev=-num;
break;
case ‘*’:
prev*=num;
break;
case ‘/’:
prev/=num;
break;
}
if(c ==‘)’){
break;
}
preOp =c;
num=0;
}
}
return sum + prev;
}
}