Middle-题目99：227. Basic Calculator II

53人阅读 评论(0)

Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
“3+2*2” = 7
” 3/2 ” = 1
” 3+5 / 2 ” = 5

public class Solution {
public int calculate(String s) {
s=s.replace(" ","");
String[] nums = s.split("[\\+\\-\\*\\/]");
List<Integer> numberList = new ArrayList<>();
for(String num : nums)
int index = 0;
for (int i = 0; i<s.length(); i++) {
char ch = s.charAt(i);
if (ch == '+' || ch == '-')
index++;
else if (ch == '*' || ch == '/') {
int op1 = numberList.get(index);
int op2 = numberList.get(index+1);
numberList.remove(index);
numberList.remove(index);
}
}

int result = numberList.get(0); index = 1;
for(int i = 0;i<s.length();i++) {
char ch = s.charAt(i);
if(ch == '+' || ch == '-')
result = operate(result, ch, numberList.get(index++));
}
return result;

}
private Integer operate(int a, char op, int b) {
if(op=='+')
return a+b;
else if(op=='-')
return a-b;
else if(op=='*')
return a*b;
else
return a/b;
}
}

90ms,beats 13.83%,众数26ms,3.63%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：63582次
• 积分：3275
• 等级：
• 排名：第10731名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论