后缀表达式 大整数(加法、乘法、gcd java)
1 import java.math.BigInteger; 2 import java.util.Scanner; 3 4 class Work { 5 String str; 6 int _num,_sym; 7 int []sym=new int[1000]; 8 BigInteger []num=new BigInteger[1000]; 9 int []w=new int[1000]; 10 11 Work() { 12 BigInteger x,y; 13 int wx,wy; 14 Scanner in=new Scanner(System.in); 15 str=in.nextLine(); 16 work(); 17 x=num[1]; 18 wx=w[1]; 19 str=in.nextLine(); 20 work(); 21 y=num[1]; 22 wy=w[1]; 23 24 if (wx>wy) 25 System.out.println("1/0"); 26 else if (wx<wy) 27 System.out.println("0/1"); 28 else 29 { 30 BigInteger z; 31 z=x.gcd(y); 32 x=x.divide(z); 33 y=y.divide(z); 34 System.out.print(x+"/"+y); 35 } 36 in.close(); 37 } 38 39 void cal() 40 { 41 if (sym[_sym]==2) 42 { 43 if (w[_num-1]<w[_num]) 44 { 45 w[_num-1]=w[_num]; 46 num[_num-1]=num[_num]; 47 } 48 else if (w[_num-1]==w[_num]) 49 num[_num-1]=num[_num-1].add(num[_num]); 50 } 51 else if (sym[_sym]==3) 52 { 53 w[_num-1]+=w[_num]; 54 num[_num-1]=num[_num-1].multiply(num[_num]); 55 } 56 _sym--; 57 _num--; 58 } 59 60 void work() 61 { 62 int len,i; 63 BigInteger z; 64 len=str.length(); 65 z=BigInteger.valueOf(1); 66 _num=0; 67 _sym=0; 68 sym[0]=0; 69 70 for (i=0;i<len;i++) 71 { 72 if (str.charAt(i)=='x') 73 { 74 num[++_num]=z; 75 w[_num]=1; 76 } 77 else 78 { 79 switch(str.charAt(i)) 80 { 81 case '+': 82 while (sym[_sym]>=2) 83 cal(); 84 sym[++_sym]=2; 85 break; 86 case '*': 87 while (sym[_sym]>=3) 88 cal(); 89 sym[++_sym]=3; 90 break; 91 case '(': 92 sym[++_sym]=1; 93 break; 94 case ')': 95 while (sym[_sym]!=1) 96 cal(); 97 _sym--; 98 break; 99 } 100 } 101 } 102 while (_sym>0) 103 cal(); 104 } 105 } 106 107 public class Main { 108 public static void main(String[] args) { 109 Work work=new Work(); 110 } 111 }