Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For user input, spaces between coefficients, operands, exponent and term are opt

ID: 3729970 • Letter: F

Question

For user input, spaces between coefficients, operands, exponent and term are
optional.

For simplicity, you can assume the following in the input format:
1. Coefficients and exponents are within the range of int type integers.
2. The polynomial is input in the format of decreasing order of exponent, with like-terms combined already.

So, user input could look like these possible situations for example:

1) 4x^3 - 2x^2 + 3x + 1

2) -4x^2 + 4x + 1

3) 4 x ^ 29 + 3 x ^ 9 - 2 x ^ 8 - 2 x ^ 6 + 10 x ^ 2 - x + 1

Since spaces do not matter, please write C++ code that can extract the coefficients and exponents of each term of ANY polynomial where the user inputs a string as the polynomial.

ALSO, library use is very limited, so cstring, cctype, cstdlib, string are alright.

Consider the following implementation declaration for Polynomial using pointers: struct ATerm {int Coefficient; int ATerm* Next; Exponent; typedef ATerm* Polynomial

Explanation / Answer

#include <iostream>
#include <string>
#include <cstdlib>
#include <cctype>
using namespace std;

struct Aterm
{
int Coefficient;
int Exponent;
Aterm* Next;
};
typedef Aterm* Polynomial;
int main()
{
int mulf,tval;
string poly,cpoly,tempstr;
getline(cin,poly);
Polynomial head,temp1;
for(int i=0; i<poly.size(); i++) // Clearing out all spaces
{
if(poly[i]!=' ')
cpoly.push_back(poly[i]);
}
if(isdigit(cpoly[0]))
mulf=1;
for(int i=0; i<cpoly.size(); i++)
{
Polynomial temp=new Aterm();
if(i!=0)
{
temp1->Next=temp;
temp1=temp;
}
else
{
head=temp;
temp1=temp;
}
temp->Exponent=1;
temp->Next=NULL;
if(cpoly[i]=='+')
{
mulf=1;
i++;
}
else if(cpoly[i]=='-')
{
mulf=-1;
i++;
}
if(cpoly[i]!='x'&&cpoly[i]!='X') //Finding Coefficient
{
tval=0;
while(i<cpoly.size()&&isdigit(cpoly[i]))
{
tval=(tval*10)+cpoly[i]-48;
i++;
}
tval*=mulf;
temp->Coefficient=tval;
}
else
temp->Coefficient=mulf;
if(i==cpoly.size())
{
temp->Exponent=0;
break;
}
if(i+1==cpoly.size())
break;

if(cpoly[i+1]!='^')
continue;
i+=2;
if(cpoly[i]=='+')
{
mulf=1;
i++;
}
else if(cpoly[i]=='-')
{
mulf=-1;
i++;
}
tval=0;
while(i<cpoly.size()&&isdigit(cpoly[i])) //Finding Exponent
{
tval=(tval*10)+cpoly[i]-48;
i++;
}
//tval*=mulf;
temp->Exponent=tval;
i--;
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote