小米2015笔试第二题

小米2015笔试第二题

求两个多项式乘积的问题相信大家在中学时经常碰到,它是这样的一个问题:
pa=an*x^n + an-1*x^(n-1) + … + a1*x + a0
pa=bm*x^m + bn-1*x^(m-1) + … + b1*x + b0
其中,an, an-1, …,a0, bm, bm-1, … ,b0 都是整数,范围[-10000, 10000]。0<=n, m <=1000。
pa*pb的结果也是一个多项式,请你编程来解决这个问题,你需要设计如何表示一个多项式并写出两个多项式相乘的程序。
C++:
string multiplyPolynormial(const string&pA,const string&pB)
Java:
String multiplyPolynormial(String pA,String pB)
其中pA和pB的格式都是“(-3,5),(87,4),(93,3),(3,0)”,表示一个多项式:-3*x^5 + 87*x^4 + 93*x^3 + 3
输入都是合法的,除了数字,左右括号和逗号没有别的任何字符,并且幂次都是从高到低排列的,输出也要求是这样一个标准的格式。

#include <iostream>
#include <string>
#include <memory.h>
#include <stdlib.h>
#include <cstring>
using namespace std;

void zhuanhuan(const string&a,int* A );
string multiplyPolynormial(const string&pA,const string&pB);

int main()
{
    string answer;
    string a;
    string b;
    cin>>a>>b;
    answer=multiplyPolynormial(a,b);
    cout<<answer<<endl;
    return 0;
}

string multiplyPolynormial(const string&pA,const string&pB)
{
    int  A[1001];
    memset(A,0,sizeof(A));
    int  B[1001];
    memset(B,0,sizeof(B));
    int  answer[2001];
    memset(answer,0,sizeof(answer));

    zhuanhuan(pA,A);
    zhuanhuan(pB,B);

    int max=0;
    for (int i=0;i<1001;i++)
    {
        if(A[i]!=0)
        {
            for(int j=0;j<1001;j++)
            {
                if(B[j]!=0)
                {
                    answer[i+j]+=A[i]*B[j];
                    if((i+j)>max)
                        max=i+j;
                }
            }
        }
    }
    string str1=""; 
    string str2="";

    char temp[10];
    memset(temp,'\0',sizeof(temp));
    string Answer="";

    for (int k=max;k>=0;k--)
    {

        if(answer[k]!=0)
        {       
            itoa(answer[k],temp,10);
            str1=temp;

            itoa(k,temp,10);
            str2=temp;

            Answer=Answer+'('+str1+','+str2+')'+',';
        }       
    }
    Answer[Answer.size()-1]='\0';
    return Answer;
}

void zhuanhuan(const string&a,int* A )
{
    string temp1="";
    string temp2="";
    bool zuoshu=true;
    for(int i=0;i<a.size();i++)
    {
        if(a[i]=='(')
        {
            temp1="";
            temp2="";
            zuoshu=true;
        }
        else
        if(a[i]==')')
        {
            A[atoi(temp2.c_str())]=atoi(temp1.c_str());
        }
        else
        if(a[i]==',')
        {
            zuoshu=!zuoshu;
        }
        else
        if(zuoshu)
        {
            temp1+=a[i];
        }
        else
        {
            temp2+=a[i];
        }
    }   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值