多项式的表示及运算

本文介绍了多项式的表示,包括项类实现可比较和可相加接口,以及多项式排序单链表类支持相加运算。此外,详细阐述了多项式类如何利用排序单链表进行多项式操作。
摘要由CSDN通过智能技术生成

可相加接口

public interface Addible<T>                      //可相加接口
{
    public void add(T t);                        //+=加法,约定两元素相加规则
    public boolean removable();                  //约定删除元素条件
}

项类,一元多项式的一项,实现可比较接口和可相加接口

public class TermX implements Comparable<TermX>,Addible<TermX> 
{
    protected int coef, exp;                               //系数coefficient和指数exponent(可为正、0)
 
    public TermX(int coef, int exp)                        //构造一项
    {
        this.coef = coef;
        this.exp = exp;
    }
    public TermX(TermX term)                               //拷贝构造方法
    {
        this(term.coef, term.exp);
    }
    
    //以“系数x^指数”的省略形式构造一元多项式的一项。
    //省略形式说明:当系数为1或-1且指数>0时,省略1,-1只写负号“-”,如x^2、-x^3;
    //当指数为0时,省略x^0,只写系数;当指数为1时,省略^1,只写x。
    public TermX(String termstr)                           
    {
        if (termstr.charAt(0)=='+')                        //去掉+号
            termstr=termstr.substring(1);
        int i = termstr.indexOf('x');
        if (i==-1)                                         //没有x,即指数为0
        {
            this.coef = Integer.parseInt(termstr);         //获得系数
            this.exp = 0;
        }
        else                                               //有x,x之前为系数,x^之后为指数
        {
            if (i==0)                                      //以x开头,即系数为1
                this.coef = 1;
            else
            {
                String sub=termstr.substring(0,i);         //x之前子中表示系数
                if (sub.equals("-"))                       //系数只有-号,即系数为1
                    this.coef=-1;
                else
                    this.coef = Integer.parseInt(sub);     //获得系数
            }
            i = termstr.indexOf('^');
            if (i==-1)
                 this.exp=1;                               //没有^,即指数为1
            else
                 this.exp = Integer.parseInt(termstr.substring(i+1));//获得指数
        }
    }

    //返回一元多项式的一项对应的“系数x^指数”的省略形式字符串,省略形式说明同TermX(String)构造方法。
    public String toString()                     
    {
        String str=this.coef>0 ? "+" : "-";                //系数的符号位
        if (this.exp==0 || this.exp>0 && this.coef!=1 && this.coef!=-1)
            str+=Math.abs(this.coef);                      //系数绝对值,省略系数1
        if (this.exp>0)
            str+="x";                                      //指数为0时,省略x^0,只写系数
        if (this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值