Description
求出在整型范围内的表达式的值,包含+,-,*,/,(,)和数字。
Input
一个合法的表达式。
Output
表达式的值(保留两位小数)。
Sample Input
((1+2)*3)+(3)
1+2*3
15/5+2
Sample Output
12.00
7.00
5.00
import java.util.Scanner;
import static java.lang.Character.isDigit;
/**
* Created by DrownFish on 2016/10/31.
*/
public class Main {
static int left[] = new int[100];
static int right[] = new int[100];
static char a[] = new char[100];
static float b[] = new float[100];
static int p[] = new int[50];
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
while(s.hasNext()){
String line = s.nextLine();
int n = line.length();
for(int i=0;i<n;i++){
a[i] = line.charAt(i);
}
int count = 0;
for(int i=1;i<n;i++){
left[i] = i-1;
}
for(int i=0;i<n;i++){
right[i] = i+1;
}
for(int i=0;i<n;i++){
if(isDigit(a[i])){
b[i] = a[i] -'0';
if(i>0 && isDigit(a[left[i]])){
b[left[i]] = b[i] + 10*b[left[i]];
link(left[i],i+1);
}
}
}
for(int i=0;i<n;i++)
{
if(a[i]=='(')
{
count++;
p[count]=i;
}
if(a[i]==')')
{
deal(p[count]+1,i-1);
b[p[count]]=b[p[count]+1];
link(p[count],i+1);
count--;
}
}
deal(0,n);
if(a[0]==' ')
System.out.printf("%.2f\r\n",b[1]);
else
System.out.printf("%.2f\r\n",b[0]);
}
}
static void link(int l,int r)
{
right[l]=r;
left[r]=l;
}
static void deal(int l,int r)
{
int i;
for(i=l;i<r;i=right[i])
{
if(a[i]=='*')
{
b[left[i]]=(b[left[i]])*(b[right[i]]);
link(left[i],right[right[i]]);
}
if(a[i]=='/')
{
b[left[i]]=(b[left[i]])/(b[right[i]]);
link(left[i],right[right[i]]);
}
}
for(i=l;i<r;i=right[i])
{
if(a[i]=='+')
{
b[left[i]]=(b[left[i]])+(b[right[i]]);
link(left[i],right[right[i]]);
}
if(a[i]=='-')
{
b[left[i]]=(b[left[i]])-(b[right[i]]);
link(left[i],right[right[i]]);
}
}
}
}