HOJ1296 Polynomial Problem
Problem Description
We have learned how to obtain the value of a polynomial when we were a middle school student. If f(x) is a polynomial of degree n, we can let
If we have x, we can get f(x) easily. But a computer can not understand the expression like above. So we had better make a program to obtain f(x).
![](http://writeblog.csdn.net/data/images/C23-1007-1.gif)
Input
There are multiple cases in this problem and ended by the EOF. In each case, there are two lines. One is an integer means x (0<=x<=10000), the other is an expression means f(x). All coefficients ai(0<=i<=n,1<=n<=10,-10000<=ai<=10000) are integers. A correct expression maybe likes 1003X^5+234X^4-12X^3-2X^2+987X-1000
Output
For each test case, there is only one integer means the value of f(x).
Sample Input
3 1003X^5+234X^4-12X^3-2X^2+987X-1000
Sample Output
264302 Notice that the writing habit of polynomial f(x) is usual such as X^6+2X^5+3X^4+4X^3+5X^2+6X+7 -X^7-5X^6+3X^5-5X^4+20X^3+2X^2+3X+9 X+1 X^3+1 X^3 -X+1 etc. Any results of middle process are in the range from -1000000000 to 1000000000.
#include<stdio.h>
#include<string.h>
#define ll __int64
char ss[2000000];
ll lmx(ll x,ll y)
{
ll i,m=1;
for(i=1;i<=y;i++)
{
m*=x;
}
return m;
}
int main()
{
char temp;
ll i,len,x,s1,s2,sum;
while(scanf("%I64d%s",&x,ss)!=EOF)
{
i=0;
temp='+';
len=strlen(ss);
s1=0;
s2=0;
sum=0;
while(i<=len)
{
if(ss[i]=='+'||ss[i]=='-'||ss[i]=='\0')
{
if(temp=='+') sum+=s1*lmx(x,s2);
else sum-=s1*lmx(x,s2);
s1=0;
s2=0;
temp=ss[i];
i++;
}
else if(ss[i]=='X')
{
if(s1==0) s1=1;
i++;
if(ss[i]!='^') s2=1;
}
else if(ss[i]=='^')
{
i++;
while(1)
{
if(ss[i]=='+'||ss[i]=='-'||ss[i]=='\0') break;
s2=s2*10+ss[i]-'0';
i++;
}
}
else
{
s1=s1*10+ss[i]-'0';
i++;
}
}
printf("%I64d\n",sum);
}
return 0;
}
#include<string.h>
#define ll __int64
char ss[2000000];
ll lmx(ll x,ll y)
{
ll i,m=1;
for(i=1;i<=y;i++)
{
m*=x;
}
return m;
}
int main()
{
char temp;
ll i,len,x,s1,s2,sum;
while(scanf("%I64d%s",&x,ss)!=EOF)
{
i=0;
temp='+';
len=strlen(ss);
s1=0;
s2=0;
sum=0;
while(i<=len)
{
if(ss[i]=='+'||ss[i]=='-'||ss[i]=='\0')
{
if(temp=='+') sum+=s1*lmx(x,s2);
else sum-=s1*lmx(x,s2);
s1=0;
s2=0;
temp=ss[i];
i++;
}
else if(ss[i]=='X')
{
if(s1==0) s1=1;
i++;
if(ss[i]!='^') s2=1;
}
else if(ss[i]=='^')
{
i++;
while(1)
{
if(ss[i]=='+'||ss[i]=='-'||ss[i]=='\0') break;
s2=s2*10+ss[i]-'0';
i++;
}
}
else
{
s1=s1*10+ss[i]-'0';
i++;
}
}
printf("%I64d\n",sum);
}
return 0;
}
为了明天所以选择坚定的执着今天。