大数乘法加法,直接java A了。
1 import java.util.Scanner; 2 import java.math.BigInteger; 3 4 public class Main { 5 public static void main(String[] args) { 6 Scanner cin = new Scanner(System.in); 7 int n; 8 int i, j, k, tmp; 9 int top; 10 boolean flag; 11 int t = 0; 12 while (cin.hasNext()) { 13 n = cin.nextInt(); 14 for (i=0; i<n; ++i) 15 buf[i] = cin.next(); 16 flag = true; 17 if ((n&1) == 0) 18 flag = false; 19 for (i=0; flag&&i<n; ++i) { 20 if ((i & 1) == 1) { 21 if (buf[i].charAt(0)!=‘+‘ && buf[i].charAt(0)!=‘*‘) 22 flag = false; 23 } else { 24 if (buf[i].charAt(0)==‘+‘ || buf[i].charAt(0)==‘*‘) 25 flag = false; 26 } 27 } 28 System.out.printf("Case %d: ", ++t); 29 if (flag==false || n==0) { 30 System.out.println("Invalid Expression!"); 31 continue; 32 } 33 top = 0; 34 bi[top++] = new BigInteger(buf[0]); 35 i = 1; 36 while (i < n) { 37 if (buf[i].charAt(0) == ‘*‘) { 38 BigInteger a = bi[top-1]; 39 BigInteger b = new BigInteger(buf[i+1]); 40 bi[top-1] = a.multiply(b); 41 } else { 42 bi[top++] = new BigInteger(buf[i+1]); 43 } 44 i += 2; 45 } 46 BigInteger sum = BigInteger.ZERO; 47 for (i=0; i<top; ++i) { 48 sum = sum.add(bi[i]); 49 } 50 System.out.println(sum.toString()); 51 } 52 } 53 54 final public static int MAXN = 25; 55 public static String[] buf = new String[MAXN]; 56 public static BigInteger[] bi = new BigInteger[MAXN]; 57 }
【HDOJ】2424 Gary's Calculator
时间: 2024-12-14 03:57:08