B - Gary's Calculator

葛深
2023-12-01

传送门:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=80660#problem/B


题意:给出一个多项式,判断是否合理,合理的话,计算结果 ,大数


import java.math.BigInteger;
import java.util.Scanner;


public class Main {


public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String[] s=new String[21];
int cas=1;
while(sc.hasNext())
{
int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=sc.next();
boolean ok=true;
if(n%2==0) ok=false;
for(int i=0;i<n;i++)
{
if(i%2==0)
{
if(s[i].equals("+")||s[i].equals("*"))
ok=false;
}
else
{
if(!s[i].equals("+")&&!s[i].equals("*"))
ok=false;
}
}
BigInteger a=BigInteger.valueOf(0);
BigInteger b=BigInteger.valueOf(0);
System.out.print("Case "+cas+": ");
cas++;
if(ok)
{
b=new BigInteger(s[0]);
for(int i=1;i<n;i+=2)
{
if(s[i].equals("+"))
{
a=a.add(b);
b=new BigInteger(s[i+1]);
}
else
b=b.multiply(new BigInteger(s[i+1]));
}
BigInteger ans=a.add(b);
System.out.println(ans);
}
else
{
System.out.println("Invalid Expression!");
}
}
}


}

 类似资料: