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
Note: Do not use the eval
built-in library function.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析过程:1.数字和计算符号之间可能存在空格;
2.当我们遍历这个字符串的时候,需要先计算乘除,再计算加减;
3 遇到加减,将数字和计算符号分别存到两个线性表中;遇到乘除,从存数字的线性表中拿出数字,然后再找到下一个数字,将计算结果设置到原来存数字的线性表的最后一个值;
4 计算加减,显然,数字线性表的长度比符号线性表的大1.遍历符号表,将当前sum加上下一个数字;
5 获取连续数字和下一次开始遍历的下标的方法。
public int calculate(String s) {
if(s==null||"".equals(s.trim())) return 0;
s=s.replaceAll("\\s","");
List<Long> list1=new ArrayList<>();
List<Character> list2=new ArrayList<>();
int i=0,len=s.length();
while(i<len){
char c=s.charAt(i);
if(c>='0'&&c<='9'){
long[] num=getNum(s,i);
list1.add(num[0]);
i=(int)num[1];
}
else if(c=='+'||c=='-'){
list2.add(c);
}
else if(c=='*'||c=='/'){
long num1[]=getNum(s,i+1);
long a1=num1[0];
int size=list1.size();
long a2=list1.get(size-1);
long snum=(c=='*')?a1*a2:a2/a1; //
list1.set(size-1,snum); //
i=(int)num1[1];
}
i++;
}
int size1=list1.size();
int size2=list2.size();
long sum=list1.get(0);
for(int j=0;j<size2;j++){
if(list2.get(j)=='+') sum+=list1.get(j+1); //
else if(list2.get(j)=='-') sum-=list1.get(j+1); //
}
return (int)sum;
}
private long[] getNum(String s,int i){
StringBuffer sb=new StringBuffer();
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){ //
sb.append(s.charAt(i));
i++;
}
String s1=sb.toString();
if(s1.length()>0) {
return new long[]{Long.parseLong(s1),i-1};
}
else return new long[]{0,i-1};
}