算法 BISHI18 多项式输出 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); in.nextToken(); int n = (int) in.nval; int[] a = new int[n + 1]; for (int i = n; i >= 0; i--) { in.nextToken(); a[i] = (int) in.nval; } for (int i = n; i >= 0; i--) { // 从最高次到0次遍历,按数学顺序输出 // 跳过系数为0的项(比如x²项系数为0,就不输出这一项) if (a[i] == 0) { continue; } // 处理符号 if (i == n) { // 最高次项 if (a[i] < 0) { // 最高次项为负,输出"-" out.print("-"); } } else { // 非最高次项 if (a[i] < 0) { // 负数输出"-" out.print("-"); } else { // 正数必须输出"+" out.print("+"); } } // 处理系数 int val = Math.abs(a[i]); // 系数绝对值≠1 或 是常数项(i=0),才输出数字;否则不输出 if (val != 1 || i == 0) { out.print(val); } // 处理x的次数格式 if (i == 1) { // 一次项:输出"x" out.print("x"); } else if (i > 1) { // 高于1次项:输出"x^次数" out.print("x^" + i); } } out.flush(); out.close(); br.close(); }