您的位置:首页 > 其它

小米2015笔试第二题

2015-04-23 22:04 183 查看

小米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];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: