第五周编程题

1 多项式加法

题目内容:

一个多项式可以表达为x的各次幂与系数乘积的和,比如:

2x6+3x5+12x3+6x+20

现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。

程序要处理的幂最大为100。

输入格式:

总共要输入两个多项式,每个多项式的输入格式如下:

每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。第一行一定是最高幂,最后一行一定是0次幂。

注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。

输出格式:

从最高幂开始依次降到0幂,如:

2x6+3x5+12x3-6x+20

注意其中的x是小写字母x,而且所有的符号之间都没有空格,如果某个幂的系数为0则不需要有那项。

输入样例:

6 2

5 3

3 12

1 6

0 20

6 2

5 3

2 12

1 6

0 20

输出样例:

4x6+6x5+12x3+12x2+12x+40

时间限制:500ms 内存限制:32000kb
在这里插入图片描述

import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int a[] = new int[101];// 存放第一个数组
		int b[] = new int[101];// 存放第二个数组
		int c[] = new int[101];// 存放第三个数组
		int m;// 幂次
		int n;// 系数
		int count = 0;//
		do {
			m = in.nextInt();
			n = in.nextInt();
			a[m] = n;
		} while (m != 0);// 输入第一个多项式
		do {
			m = in.nextInt();
			n = in.nextInt();
			b[m] = n;
		} while (m != 0);
		for (int i = 0; i < 101; i++) {
			c[i] = a[i] + b[i];// 合并多项式
		}
		for (int i = 100; i > 1; i--) {
			if (c[i] != 0)// 系数不为0
			{
				if (count > 0)// 不是输出的第一项
				{
					if (c[i] > 0) {
						System.out.print("+");
					}
				}
				if (c[i] != 1 && c[i] != -1) {
					System.out.print(c[i] + "x" + i);
				} else if (c[i] == 1) {
					System.out.print("x" + i);
				} else {
					System.out.print("-x" + i);
				}
				count++;
			} else {
				continue;
			}
		}
		if (c[0] != 0) {
			if (count > 0) {
				if (c[1] > 0) {
					System.out.print("+");
				}
			}
			if (c[1] != 1 && c[1] != -1) {
				System.out.print(c[1] + "x");
			} else if (c[1] == 1) {
				System.out.print("x");
			} else {
				System.out.print("-x");
			}
			count++;
		}
		if (c[0] != 0) {
			if (count > 0) {
				if (c[1] > 0) {
					System.out.print("+");
				}
			}
			System.out.print(c[0]);
			count++;
		}

		if (count == 0) {
			System.out.print("0");
		}
		in.close();
	}
}

参考:https://blog.csdn.net/weixin_43398418/article/details/115547172

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值