您的位置:首页 > 其它

227. Basic Calculator II

2016-03-31 01:20 363 查看
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 static int calculate(String s) {
s = s.replaceAll("\\s+", "");
int result = 0;
int num = 0;
int sign = 1;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '+'){
result += num * sign;
num = 0;
sign = 1;
continue;
}else if(c == '-'){
result += num *sign;
num = 0;
sign = -1;
continue;
}else if(c == '*'){
int num2 = 0;
while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){//don't forget the first condition
num2 = num2*10 + s.charAt(i + 1) - '0';
i++;
}
num *= num2;
}else if(c == '/'){
int num2 = 0;
while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){//don't forget the first condition
num2 = num2*10 + s.charAt(i + 1) - '0';
i++;
}
num /= num2;
}else{
num = num*10 + c - '0';
}
}
if(num != 0){
result += sign * num;
}
return (int)result;
}
public static void main(String[] args) {
String s = "3+2*2-1";
String s2 = "3/2";
String s3 = " 3+5 / 2 ";
String s4 = "1*2*3*4*5*6*7*8*9*10";
String s5 = "100000000/1/2/3/4/5/6/7/8/9/10";
System.out.println(calculate(s5));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: