In: Computer Science
How to write a C++ program that lets the user enter a string and checks if it is an accepted polynomial. Accepted polynomials need to have one term per degree, no parentheses, spaces ignored.
#include <iostream>
#include<cctype>
#include<algorithm>
using namespace std;
int main()
{
string s;
getline(cin,s);
s.erase(remove(s.begin(),s.end(),' '),s.end());
int d;
int flag=0;
if(s.length()>=4)
{ d=s[3];
if(!isdigit(d))
{
flag=1;
}
}
for(int i=0;i<s.length();i++)
{
if(s[i]=='('|| s[i]==')')
{
flag=1;
break;
}
else if(s[i]==' ')
continue;
else if(isdigit(s[i]) && (i+4)<s.length())
{
if(s[i+1]=='x')
{
if(s[i+2]=='^')
{
if(isdigit(s[i+3]))
{
if(d==s[i+3])
{
d--;
if(s[i+4]=='+' || s[i+4]=='-')
{
i+=4;
}
else
{
flag=1;
break;
}
}
else
{
flag=1;
break;
}
}
else
{
flag=1;
break;
}
}
else
{
flag=1;
break;
}
}
else
{
flag=1;
break;
}
}
else if(i==s.length()-1)
{
if(!isdigit(s[i]))
{
flag=1;
break;
}
}
else
{
flag=1;
break;
}
}
if(flag==1 || !isdigit(s[s.length()-1]))
cout<<"Not Accepted";
else
cout<<"Accepted";
return 0;
}
OUTPUT:
NOTE:
STRING SHOULD BE OF FORMAT LIKE ax^3+bx^2+cx^1+d
where a,b,c,d are numeric values.